PluginProbe
MainWP Dashboard: Self-hosted WordPress Management for Agencies / 6.2.2
MainWP Dashboard: Self-hosted WordPress Management for Agencies v6.2.2
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 +4820 -3417 5.0.3 → 6.2.2 View file →
@@ -1,218 +1,343 @@
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 +globalThis.mainwpVars = globalThis.mainwpVars || {};
5 +
4 6 jQuery(function ($) {
5 7
6 - if (jQuery('.mainwp-ui-page').length) {
7 - jQuery('.mainwp-popup-tooltip').popup()
8 - }
8 + if (jQuery('.mainwp-ui-page').length) {
9 + jQuery('.mainwp-popup-tooltip').popup()
10 + }
9 11
10 - // review for new UI update
11 - jQuery(document).on('click', '#mainwp-category-add-submit', function () {
12 - var newCat = jQuery('#newcategory').val();
13 - if (jQuery('#categorychecklist .menu').find('.item[data-value="' + encodeURIComponent(newCat) + '"]').length > 0) {
14 - console.log('Existed: ' + encodeURIComponent(newCat));
15 - jQuery('#newcategory').val('');
16 - return;
17 - }
18 - var selected_categories = jQuery('#categorychecklist').dropdown('get value');
19 - jQuery('#categorychecklist .menu').append('<div class="item" data-value="' + encodeURIComponent(newCat) + '">' + newCat + '</div>');
20 - jQuery('#categorychecklist .menu').dropdown('set selected', selected_categories); // to refresh.
21 - jQuery('#newcategory').val('');
22 - });
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 + },
23 24
24 - // Show/Hide new category field and button
25 - jQuery('#category-add-toggle').on('click', function () {
26 - jQuery('#newcategory-field').toggle();
27 - jQuery('#mainwp-category-add-submit-field').toggle();
28 - return false;
29 - });
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 + });
30 32
31 - // Manage Child options
32 - $('.mainwp-parent-toggle input[type="checkbox"]').on('change', function () {
33 - if (this.checked) {
34 - $(this).closest('.mainwp-parent-toggle').next('.mainwp-child-field').fadeIn();
35 - } else {
36 - $(this).closest('.mainwp-parent-toggle').next('.mainwp-child-field').fadeOut();
37 - }
38 - });
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', ' ');
39 37
40 - //Toggle Add Site form
41 - jQuery('#mainwp_managesites_verify_installed_child').on('change', function () {
42 - if (jQuery(this).is(':checked')) {
43 - jQuery('#mainwp-add-site-hidden-form').fadeIn(500);
44 - } else {
45 - jQuery('#mainwp-add-site-hidden-form').fadeOut(500);
46 - }
47 - });
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 + });
48 47
49 - // Toggle Add Site / Optional Settings section
50 - jQuery('#mainwp-add-site-advanced-options-toggle').on('click', function () {
51 - jQuery('#mainwp-add-site-advanced-options').toggle(500);
52 - return false;
53 - });
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 + });
54 54
55 - jQuery('.mainwp-remove-site-button').on('click', function () {
56 - var side_id = jQuery(this).attr('site-id');
57 - var confirmation = "Are you sure you want to remove this site from your MainWP Dashboard?";
58 - mainwp_confirm(confirmation, function () {
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 + });
59 63
60 - feedback('mainwp-message-zone', '<i class="notched circle loading icon"></i> ' + __('Removing the site. Please wait...', 'mainwp'), '');
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 + });
61 72
62 - var data = mainwp_secure_data({
63 - action: 'mainwp_removesite',
64 - id: side_id
65 - });
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 + });
66 78
67 - jQuery.post(ajaxurl, data, function (response) {
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?";
68 82
69 - var error = false;
83 + let _confirm_callback = mainwp_get_remove_calback(side_id);
70 84
71 - if (response.error != undefined) {
72 - error = response.error;
73 - } else if (response.result == 'SUCCESS') {
74 - 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');
75 - } else if (response.result == 'NOSITE') {
76 - feedback('mainwp-message-zone', __('Site could not be removed. Please reload the page and try again.', 'mainwp'), 'red');
77 - error = true;
78 - } else {
79 - 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');
80 - }
85 + mainwp_confirm(confirmation, _confirm_callback, false, false, false, 'REMOVE');
81 86
82 - if (error == false) {
83 - setTimeout(function () {
84 - window.location = 'admin.php?page=managesites';
85 - }, 3000);
86 - }
87 + return false;
88 + });
87 89
88 - }, 'json');
89 - }, false, false, false, 'REMOVE');
90 +});
90 91
91 - return false;
92 - });
92 +let mainwp_get_remove_calback = function (side_id) {
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 + });
93 99
94 -});
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) {
95 106
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.');
109 +
110 + let error_msg = '';
111 +
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 + }
116 +
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 + }
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 +
199 +}
200 +
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 + }
207 +
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 + }
214 +
215 + if (true === show || (false !== show && msg_html)) {
216 + jQuery(zone_selector).show();
217 + } else {
218 + jQuery(zone_selector).hide();
219 + }
220 +};
221 +
222 +let bulkInstallMaxThreads = mainwpParams['maximumInstallUpdateRequests'] == undefined ? 3 : mainwpParams['maximumInstallUpdateRequests'];
223 +let bulkInstallCurrentThreads = 0;
224 +let bulkInstallDone = 0;
225 +
96 226 /**
97 227 * Global
98 228 */
99 229 jQuery(function () {
100 - jQuery('.mainwp-row').on({
101 - mouseenter: function () {
102 - rowMouseEnter(this);
103 - },
104 - mouseleave: function () {
105 - rowMouseLeave(this);
106 - }
107 - });
230 + jQuery('.mainwp-row').on({
231 + mouseenter: function () {
232 + rowMouseEnter(this);
233 + },
234 + mouseleave: function () {
235 + rowMouseLeave(this);
236 + }
237 + });
108 238 });
109 -rowMouseEnter = function (elem) {
110 - if (!jQuery(elem).children('.mainwp-row-actions-working').is(":visible"))
111 - jQuery(elem).children('.mainwp-row-actions').show();
239 +let rowMouseEnter = function (elem) {
240 + if (!jQuery(elem).children('.mainwp-row-actions-working').is(":visible"))
241 + jQuery(elem).children('.mainwp-row-actions').show();
112 242 };
113 -rowMouseLeave = function (elem) {
114 - if (jQuery(elem).children('.mainwp-row-actions').is(":visible"))
115 - jQuery(elem).children('.mainwp-row-actions').hide();
243 +let rowMouseLeave = function (elem) {
244 + if (jQuery(elem).children('.mainwp-row-actions').is(":visible"))
245 + jQuery(elem).children('.mainwp-row-actions').hide();
116 246 };
117 247
118 -
119 -mainwp_sidebar_position_onchange = function (me) {
120 - jQuery(me).closest("form").submit();
121 -}
122 -
123 248 /**
124 249 * Recent posts
125 250 */
126 -jQuery(document).ready(function () {
127 - jQuery(document).on('click', '.mainwp-post-unpublish', function () {
128 - postAction(jQuery(this), 'unpublish');
129 - return false;
130 - });
131 - jQuery(document).on('click', '.mainwp-post-publish', function () {
132 - postAction(jQuery(this), 'publish');
133 - return false;
134 - });
135 - jQuery(document).on('click', '.mainwp-post-trash', function () {
136 - postAction(jQuery(this), 'trash');
137 - return false;
138 - });
139 - jQuery(document).on('click', '.mainwp-post-restore', function () {
140 - postAction(jQuery(this), 'restore');
141 - return false;
142 - });
143 - jQuery(document).on('click', '.mainwp-post-delete', function () {
144 - postAction(jQuery(this), 'delete');
145 - return false;
146 - });
251 +jQuery(function () {
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 + });
147 272
148 273 });
149 274
150 275 // Publish, Unpublish, Trash, ... posts and pages
151 -postAction = function (elem, what) {
152 - var rowElement = jQuery(elem).closest('.grid');
153 - var postId = rowElement.children('.postId').val();
154 - var websiteId = rowElement.children('.websiteId').val();
276 +let postAction = function (elem, what) {
277 + let rowElement = jQuery(elem).closest('.grid');
278 + let postId = rowElement.children('.postId').val();
279 + let websiteId = rowElement.children('.websiteId').val();
155 280
156 - var data = mainwp_secure_data({
157 - action: 'mainwp_post_' + what,
158 - postId: postId,
159 - websiteId: websiteId
160 - });
161 - rowElement.hide();
162 - rowElement.next('.mainwp-row-actions-working').show();
163 - jQuery.post(ajaxurl, data, function (response) {
164 - if (response.error) {
165 - rowElement.show();
166 - rowElement.next('.mainwp-row-actions-working').hide();
167 - rowElement.html('<div class="sixteen wide column"><i class="times red icon"></i> ' + response.error + '</div>');
168 - } else if (response.result) {
169 - rowElement.show();
170 - rowElement.next('.mainwp-row-actions-working').hide();
171 - rowElement.html('<div class="sixteen wide column"><i class="check green icon"></i>' + response.result + '</div>');
172 - } else {
173 - rowElement.show();
174 - rowElement.next('.mainwp-row-actions-working').hide();
175 - }
176 - }, 'json');
177 - 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;
178 303 };
179 304
180 305
181 -mainwp_post_posting_start_next = function (start) {
182 - if (typeof start !== "undefined" && start) {
183 - bulkInstallDone = 0;
184 - bulkInstallCurrentThreads = 0;
185 - bulkInstallTotal = jQuery('.site-bulk-posting[status="queue"]').length;
186 - }
187 - while ((siteToPosting = jQuery('.site-bulk-posting[status="queue"]:first')) && (siteToPosting.length > 0) && (bulkInstallCurrentThreads < bulkInstallMaxThreads)) {
188 - mainwp_post_posting_start_specific(siteToPosting);
189 - }
306 +let mainwp_post_posting_start_next = function (start) {
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 + }
190 315 };
191 316
192 -mainwp_post_posting_start_specific = function (siteToPosting) {
193 - siteToPosting.attr('status', 'progress');
194 - bulkInstallDone++;
195 - bulkInstallCurrentThreads++;
196 - var data = mainwp_secure_data({
197 - action: 'mainwp_post_postingbulk',
198 - post_id: jQuery('#bulk_posting_id').val(),
199 - site_id: jQuery(siteToPosting).attr('site-id'),
200 - count: bulkInstallDone,
201 - total: bulkInstallTotal,
202 - delete_bulkpost: (bulkInstallDone == bulkInstallTotal) ? true : false
203 - });
204 - siteToPosting.find('.progress').html('<i class="notched circle loading icon"></i>');
205 - jQuery.post(ajaxurl, data, function (response) {
206 - bulkInstallCurrentThreads--;
207 - if (response && response.result) {
208 - siteToPosting.find('.progress').html(response.result);
209 - if (response.edit_link !== '') {
210 - siteToPosting.after(response.edit_link);
211 - }
212 - }
213 - mainwp_post_posting_start_next();
214 - }, 'json');
317 +let mainwp_post_posting_start_specific = function (siteToPosting) {
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');
215 340 }
216 341
217 342
218 343 /**
@@ -217,237 +342,211 @@
217 342
218 343 /**
219 344 * Plugins Widget
220 345 */
221 -jQuery(document).ready(function () {
222 - jQuery(document).on('click', '.mainwp-plugin-deactivate', function () {
223 - pluginAction(jQuery(this), 'deactivate');
224 - return false;
225 - });
226 - jQuery(document).on('click', '.mainwp-plugin-activate', function () {
227 - pluginAction(jQuery(this), 'activate');
228 - return false;
229 - });
230 - jQuery(document).on('click', '.mainwp-plugin-delete', function () {
231 - pluginAction(jQuery(this), 'delete');
232 - return false;
233 - });
346 +jQuery(function () {
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 + });
234 363 });
235 364
236 365
237 -pluginAction = function (elem, what) {
238 - var rowElement = jQuery(elem).parent().parent();
239 - var plugin = rowElement.children('.pluginSlug').val();
240 - var websiteId = rowElement.children('.websiteId').val();
366 +let pluginAction = function (elem, what) {
367 + let rowElement = jQuery(elem).closest('.row-manage-item');
368 + let plugin = rowElement.children('.pluginSlug').val();
369 + let websiteId = rowElement.children('.websiteId').val();
241 370
242 - var data = mainwp_secure_data({
243 - action: 'mainwp_widget_plugin_' + what,
244 - plugin: plugin,
245 - websiteId: websiteId
246 - });
247 - rowElement.children().hide();
248 - rowElement.children('.mainwp-row-actions-working').show();
249 - jQuery.post(ajaxurl, data, function (response) {
250 - if (response && response.error) {
251 - rowElement.children().show();
252 - rowElement.html(response.error);
253 - } else if (response && response.result) {
254 - rowElement.children().show();
255 - rowElement.html(response.result);
256 - } else {
257 - rowElement.children('.mainwp-row-actions-working').hide();
258 - }
259 - }, 'json');
260 -
261 - 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;
262 378 };
263 379
264 380 /**
265 381 * Themes Widget
266 382 */
267 -jQuery(document).ready(function () {
268 - jQuery(document).on('click', '.mainwp-theme-activate', function () {
269 - themeAction(jQuery(this), 'activate');
270 - return false;
271 - });
272 - jQuery(document).on('click', '.mainwp-theme-delete', function () {
273 - themeAction(jQuery(this), 'delete');
274 - return false;
275 - });
383 +jQuery(function () {
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 + });
276 396 });
277 397
278 -themeAction = function (elem, what) {
279 - var rowElement = jQuery(elem).parent().parent();
280 - var theme = rowElement.children('.themeSlug').val();
281 - var websiteId = rowElement.children('.websiteId').val();
398 +let themeAction = function (elem, what) {
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;
409 +};
282 410
283 - var data = mainwp_secure_data({
284 - action: 'mainwp_widget_theme_' + what,
285 - theme: theme,
286 - websiteId: websiteId
287 - });
288 - rowElement.children().hide();
289 - rowElement.children('.mainwp-row-actions-working').show();
290 - jQuery.post(ajaxurl, data, function (response) {
291 - if (response && response.error) {
292 - rowElement.children().show();
293 - rowElement.html(response.error);
294 - } else if (response && response.result) {
295 - rowElement.children().show();
296 - rowElement.html(response.result);
297 - } else {
298 - rowElement.children('.mainwp-row-actions-working').hide();
299 - }
300 - }, 'json');
411 +let plugin_theme_doAction = function (data, rowElement) {
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');
425 +};
301 426
302 - return false;
303 -};
304 427
305 428 // offsetRelative (or, if you prefer, positionRelative)
306 429 (function ($) {
307 - $.fn.offsetRelative = function (top) {
308 - var $this = $(this);
309 - var $parent = $this.offsetParent();
310 - var offset = $this.position();
311 - if (!top)
312 - return offset; // Didn't pass a 'top' element
313 - else if ($parent.get(0).tagName == "BODY")
314 - return offset; // Reached top of document
315 - else if ($(top, $parent).length)
316 - return offset; // Parent element contains the 'top' element we want the offset to be relative to
317 - else if ($parent[0] == $(top)[0])
318 - return offset; // Reached the 'top' element we want the offset to be relative to
319 - else { // Get parent's relative offset
320 - var parent_offset = $parent.offsetRelative(top);
321 - offset.top += parent_offset.top;
322 - offset.left += parent_offset.left;
323 - return offset;
324 - }
325 - };
326 - $.fn.positionRelative = function (top) {
327 - return $(this).offsetRelative(top);
328 - };
329 -}(jQuery));
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 + };
452 +})(jQuery);
330 453
331 -var hidingSubMenuTimers = {};
332 -jQuery(document).ready(function () {
333 - // jQuery('span[id^=mainwp]').each(function () {
334 - // jQuery(this).parent().parent().on("mouseenter", function () {
335 - // var spanEl = jQuery(this).find('span[id^=mainwp]');
336 - // var spanId = /^mainwp-(.*)$/.exec(spanEl.attr('id'));
337 - // if (spanId) {
338 - // if (hidingSubMenuTimers[spanId[1]]) {
339 - // clearTimeout(hidingSubMenuTimers[spanId[1]]);
340 - // }
341 - // var currentMenu = jQuery('#menu-mainwp-' + spanId[1]);
342 - // var offsetVal = jQuery(this).offset();
343 - // currentMenu.css('left', offsetVal.left + jQuery(this).outerWidth() - 30);
344 -
345 - // currentMenu.css('top', offsetVal.top - 15 - jQuery(this).outerHeight()); // + tmp);
346 - // subMenuIn(spanId[1]);
347 - // }
348 - // }).on("mouseleave", function () {
349 - // var spanEl = jQuery(this).find('span[id^=mainwp]');
350 - // var spanId = /^mainwp-(.*)$/.exec(spanEl.attr('id'));
351 - // if (spanId) {
352 - // hidingSubMenuTimers[spanId[1]] = setTimeout(function (span) {
353 - // return function () {
354 - // subMenuOut(span);
355 - // };
356 - // }(spanId[1]), 30);
357 - // }
358 - // });
359 - // });
360 - jQuery('.mainwp-submenu-wrapper').on({
361 - mouseenter: function () {
362 - var spanId = /^menu-mainwp-(.*)$/.exec(jQuery(this).attr('id'));
363 - if (spanId) {
364 - if (hidingSubMenuTimers[spanId[1]]) {
365 - clearTimeout(hidingSubMenuTimers[spanId[1]]);
454 +let hidingSubMenuTimers = {};
455 +jQuery(function () {
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 + }
366 474 }
367 - }
368 - },
369 - mouseleave: function () {
370 - var spanId = /^menu-mainwp-(.*)$/.exec(jQuery(this).attr('id'));
371 - if (spanId) {
372 - hidingSubMenuTimers[spanId[1]] = setTimeout(function (span) {
373 - return function () {
374 - subMenuOut(span);
375 - };
376 - }(spanId[1]), 30);
377 - }
378 - }
379 - });
475 + });
380 476 });
381 -subMenuIn = function (subName) {
382 - jQuery('#menu-mainwp-' + subName).show();
383 - jQuery('#mainwp-' + subName).parent().parent().addClass('hoverli');
384 - jQuery('#mainwp-' + subName).parent().parent().css('background-color', '#EAF2FA');
385 - jQuery('#mainwp-' + subName).css('color', '#333');
477 +let subMenuOut = function (subName) {
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', '');
386 482 };
387 -subMenuOut = function (subName) {
388 - jQuery('#menu-mainwp-' + subName).hide();
389 - jQuery('#mainwp-' + subName).parent().parent().css('background-color', '');
390 - jQuery('#mainwp-' + subName).parent().parent().removeClass('hoverli');
391 - jQuery('#mainwp-' + subName).css('color', '');
392 -};
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 +}
393 515
394 -mainwp_js_get_error_not_detected_connect = function (jsonStr, what, elemId, retErrText) {
395 - if (undefined !== jsonStr && '' != jsonStr && undefined !== what && 'html_msg' === what) {
396 - try {
397 - var obj_err = JSON.parse(jsonStr);
398 - if (typeof obj_err === 'object') {
399 - if (obj_err.el_before !== undefined && obj_err.el_link !== undefined && obj_err.el_text !== undefined) {
400 - var elafter = obj_err.el_after !== undefined ? obj_err.el_after : '';
401 - if (true === retErrText) {
402 - return obj_err.el_before + obj_err.el_text + elafter;
403 - }
404 - if (undefined !== elemId && '' != elemId) {
405 - var el = document.createElement('a');
406 - el.text = obj_err.el_text;
407 - el.href = obj_err.el_link;
408 - el.target = "_blank";
409 - console.log(el);
410 - jQuery('#' + elemId).html('').append(document.createTextNode(obj_err.el_before), el, document.createTextNode(elafter));
411 - feedback_scroll(elemId, 'red');
412 - }
413 - return true;
414 - }
415 - } else {
416 - return false; // it is not or invalid json.
417 - }
418 - } catch (e) {
419 - 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;
420 521 }
421 - }
422 - 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.');
423 522 }
424 523
425 524 function shake_element(select) {
426 - var pos = jQuery(select).position();
427 - var type = jQuery(select).css('position');
525 + let pos = jQuery(select).position();
526 + let type = jQuery(select).css('position');
428 527
429 - if (type == 'static') {
430 - jQuery(select).css({
431 - position: 'relative'
432 - });
433 - }
528 + if (type == 'static') {
529 + jQuery(select).css({
530 + position: 'relative'
531 + });
532 + }
434 533
435 - if (type == 'static' || type == 'relative') {
436 - pos.top = 0;
437 - pos.left = 0;
438 - }
534 + if (type == 'static' || type == 'relative') {
535 + pos.top = 0;
536 + pos.left = 0;
537 + }
439 538
440 - jQuery(select).data('init-type', type);
539 + jQuery(select).data('init-type', type);
441 540
442 - var 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]];
443 542
444 - for (s = 0; s < shake.length; s++) {
445 - jQuery(select).animate({
446 - top: pos.top + shake[s][0],
447 - left: pos.left + shake[s][1]
448 - }, shake[s][2], 'linear');
449 - }
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 + }
450 549 }
451 550
452 551
453 552 /**
@@ -452,62 +551,93 @@
452 551
453 552 /**
454 553 * Required
455 554 */
456 -feedback = function (id, text, type, append) {
457 - if (append == true) {
458 - var currentHtml = jQuery('#' + id).html();
459 - if (currentHtml == null)
460 - currentHtml = "";
461 - if (currentHtml != '') {
462 - 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);
463 570 } else {
464 - 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);
465 576 }
466 - jQuery('#' + id).html(currentHtml);
467 - jQuery('#' + id).removeClass('yellow');
468 - jQuery('#' + id).removeClass('green');
469 - jQuery('#' + id).removeClass('red');
470 - jQuery('#' + id).addClass(type);
471 - } else {
472 - jQuery('#' + id).html(text);
473 - jQuery('#' + id).removeClass('yellow');
474 - jQuery('#' + id).removeClass('green');
475 - jQuery('#' + id).removeClass('red');
476 - jQuery('#' + id).addClass(type);
477 - }
478 - jQuery('#' + id).show();
577 + jQuery('#' + id).show();
479 578
480 - // automatically scroll to error message if it's not visible
481 - scrollElementTop(id);
579 + // automatically scroll to error message if it's not visible
580 + scrollElementTop(id);
482 581 };
483 582
484 -feedback_scroll = function (id, color) {
485 - jQuery('#' + id).removeClass('green red yellow');
486 - jQuery('#' + id).addClass(color);
487 - jQuery('#' + id).show();
488 - // automatically scroll to error message if it's not visible
489 - 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);
490 589 }
491 590
492 -scrollElementTop = function (id) {
493 - var scrolltop = jQuery(window).scrollTop();
494 - if (jQuery('#' + id).length == 0) {
495 - return;
496 - }
497 - var off = jQuery('#' + id).offset();
498 - if (scrolltop > off.top - 40)
499 - jQuery('html, body').animate({
500 - scrollTop: off.top - 40
501 - }, 1000, function () {
502 - shake_element('#' + id)
503 - });
504 - else
505 - 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 :)
506 605 }
507 606
508 -jQuery(document).ready(function () {
509 - jQuery('div.mainwp-hidden').parent().parent().css("display", "none");
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 +
638 +jQuery(function () {
639 + jQuery('div.mainwp-hidden').parent().parent().css("display", "none");
510 640 });
511 641
512 642 /**
513 643 * Security Issues
@@ -512,1861 +642,2016 @@
512 642 /**
513 643 * Security Issues
514 644 */
515 645
516 -var 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'];
517 -jQuery(document).ready(function () {
518 - var securityIssueSite = jQuery('#securityIssueSite');
519 - if ((securityIssueSite.val() != null) && (securityIssueSite.val() != "")) {
520 - jQuery(document).on('click', '#securityIssues_fixAll', function () {
521 - securityIssues_fix('all');
522 - });
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'];
647 +jQuery(function () {
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 + });
523 663
524 - jQuery(document).on('click', '#securityIssues_refresh', function () {
525 - for (var i = 0; i < securityIssues_fixes.length; i++) {
526 - var securityIssueCurrentIssue = jQuery('#' + securityIssues_fixes[i] + '_fix');
527 - if (securityIssueCurrentIssue) {
528 - securityIssueCurrentIssue.hide();
529 - }
530 - jQuery('#' + securityIssues_fixes[i] + '_extra').hide();
531 - jQuery('#' + securityIssues_fixes[i] + '_ok').hide();
532 - jQuery('#' + securityIssues_fixes[i] + '_nok').hide();
533 - jQuery('#' + securityIssues_fixes[i] + '_loading').show();
534 - }
535 - securityIssues_request(jQuery('#securityIssueSite').val());
536 - });
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));
537 674
538 - for (var i = 0; i < securityIssues_fixes.length; i++) {
539 - jQuery('#' + securityIssues_fixes[i] + '_fix').on('click', function (what) {
540 - return function () {
541 - securityIssues_fix(what);
542 - return false;
675 + jQuery('#' + ise + '_unfix').on('click', function (what) {
676 + return function () {
677 + securityIssues_unfix(what);
678 + return false;
679 + }
680 + }(ise));
543 681 }
544 - }(securityIssues_fixes[i]));
545 -
546 - jQuery('#' + securityIssues_fixes[i] + '_unfix').on('click', function (what) {
547 - return function () {
548 - securityIssues_unfix(what);
549 - return false;
550 - }
551 - }(securityIssues_fixes[i]));
682 + securityIssues_request(securityIssueSite.val());
552 683 }
553 - securityIssues_request(securityIssueSite.val());
554 - }
555 684 });
556 -securityIssues_fix = function (feature) {
557 - if (feature == 'all') {
558 - for (var i = 0; i < securityIssues_fixes.length; i++) {
559 - if (jQuery('#' + securityIssues_fixes[i] + '_nok').css('display') != 'none') {
560 - if (jQuery('#' + securityIssues_fixes[i] + '_fix')) {
561 - jQuery('#' + securityIssues_fixes[i] + '_fix').hide();
562 - }
563 - jQuery('#' + securityIssues_fixes[i] + '_extra').hide();
564 - jQuery('#' + securityIssues_fixes[i] + '_ok').hide();
565 - jQuery('#' + securityIssues_fixes[i] + '_nok').hide();
566 - jQuery('#' + securityIssues_fixes[i] + '_loading').show();
567 - }
568 - }
569 - } else {
685 +globalThis.securityIssues_fix = function (feature) {
570 686 if (jQuery('#' + feature + '_fix')) {
571 - jQuery('#' + feature + '_fix').hide();
687 + jQuery('#' + feature + '_fix').hide();
572 688 }
573 689 jQuery('#' + feature + '_extra').hide();
574 690 jQuery('#' + feature + '_ok').hide();
575 691 jQuery('#' + feature + '_nok').hide();
576 692 jQuery('#' + feature + '_loading').show();
577 - }
578 693
579 - var data = mainwp_secure_data({
580 - action: 'mainwp_security_issues_fix',
581 - feature: feature,
582 - id: jQuery('#securityIssueSite').val()
583 - });
694 + let data = mainwp_secure_data({
695 + action: 'mainwp_security_issues_fix',
696 + feature: feature,
697 + id: jQuery('#securityIssueSite').val()
698 + });
584 699
585 - jQuery.post(ajaxurl, data, function (response) {
586 - securityIssues_handle(response);
587 - }, 'json');
700 + jQuery.post(ajaxurl, data, function (response) {
701 + securityIssues_handle(response);
702 + }, 'json');
588 703 };
589 704
590 -// Securtiy issues Widget
705 +let securityIssues_unfix = function (feature) {
706 + if (jQuery('#' + feature + '_unfix')) {
707 + jQuery('#' + feature + '_unfix').hide();
708 + }
709 + jQuery('#' + feature + '_extra').hide();
710 + jQuery('#' + feature + '_ok').hide();
711 + jQuery('#' + feature + '_nok').hide();
712 + jQuery('#' + feature + '_loading').show();
591 713
592 -// Show/Hide the list
593 -jQuery(document).on('click', '#show-security-issues-widget-list', function () {
594 - jQuery('#mainwp-security-issues-widget-list').toggle();
595 - return false;
596 -});
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');
722 +};
723 +let securityIssues_request = function (websiteId) {
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');
731 +};
732 +// eslint-disable-next-line complexity
733 +let securityIssues_handle = function (response) { // NOSONAR - complex.
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 + }
597 749
598 -// Fix all sites all security issues
599 -jQuery(document).on('click', '.fix-all-security-issues', function () {
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 + }
600 756
601 - jQuery('#mainwp-secuirty-issues-loader').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();
602 764
603 - jQuery('#mainwp-security-issues-widget-list').show();
604 - bulkInstallTotal = jQuery('#mainwp-security-issues-widget-list .item[status="queue"]').length;
605 - jQuery('.fix-all-site-security-issues').addClass('disabled');
606 - jQuery('.unfix-all-site-security-issues').addClass('disabled');
607 - mainwp_fix_all_security_issues_start_next();
608 -});
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 + }
609 771
610 -mainwp_fix_all_security_issues_start_next = function () {
611 - while ((siteToFix = jQuery('#mainwp-security-issues-widget-list .item[status="queue"]:first')) && (siteToFix.length > 0) && (bulkInstallCurrentThreads < bulkInstallMaxThreads)) {
612 - mainwp_fix_all_security_issues_specific(siteToFix);
613 - }
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 + }
779 +
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 + }
789 + }
790 + } catch {
791 + result = '<i class="exclamation circle icon"></i> ' + MainWP.I18n.t('Undefined error!');
792 + }
793 + }
794 + if (result != '') {
795 + //show error!
796 + }
797 +};
798 +
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); });
614 807 }
615 808
616 -mainwp_fix_all_security_issues_specific = function (siteToFix) {
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 + });
617 813
618 - bulkInstallCurrentThreads++;
814 + if ('all' == siteIds) {
815 + siteIds = allWebsiteIds;
816 + }
619 817
620 - siteToFix.attr('status', 'progress');
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;
831 + }
621 832
622 - var data = mainwp_secure_data({
623 - action: 'mainwp_security_issues_fix',
624 - feature: 'all',
625 - id: siteToFix.attr('siteid')
626 - });
833 + let nrOfWebsites = allWebsiteIds.length;
627 834
628 - var el = siteToFix.find('.fix-all-site-security-issues');
629 - el.hide();
630 -
631 - jQuery.post(ajaxurl, data, function () {
632 - return function () {
633 - siteToFix.attr('status', 'done');
634 - el.show();
635 - bulkInstallCurrentThreads--;
636 - bulkInstallDone++;
637 - if (bulkInstallDone != 0 && (bulkInstallTotal == 1 || (bulkInstallDone >= bulkInstallTotal))) {
638 - window.location.href = location.href;
639 - }
640 - mainwp_fix_all_security_issues_start_next();
835 + if (nrOfWebsites == 0) {
836 + managesites_reset_bulk_actions_params();
837 + return;
641 838 }
642 - }(), 'json');
643 -}
644 839
645 -// Fix all securtiy issues for a site
646 -jQuery(document).on('click', '.fix-all-site-security-issues', function () {
647 - jQuery('#mainwp-secuirty-issues-loader').show();
648 - mainwp_fix_all_security_issues(jQuery(this).closest('.item').attr('siteid'), true);
649 -});
840 + let siteNames = {};
650 841
651 -mainwp_fix_all_security_issues = function (siteId, refresh) {
652 - var data = mainwp_secure_data({
653 - action: 'mainwp_security_issues_fix',
654 - feature: 'all',
655 - id: siteId
656 - });
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');
845 + }
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);
657 856
658 - var el = jQuery('#mainwp-security-issues-widget-list .item[siteid="' + siteId + '"] .fix-all-site-security-issues');
857 + mainwp_managesites_check_abandoned_all_int(allWebsiteIds, which);
858 +};
659 859
660 - el.hide();
860 +let mainwp_managesites_check_abandoned_all_int = function (websiteIds, which) {
861 + mainwpVars.websitesToUpgrade = websiteIds;
862 + mainwpVars.currentWebsite = 0;
863 + mainwpVars.websitesDone = 0;
864 + mainwpVars.websitesTotal = mainwpVars.websitesToUpgrade.length;
865 + mainwpVars.websitesLeft = mainwpVars.websitesToUpgrade.length;
661 866
662 - jQuery('.fix-all-site-security-issues').addClass('disabled');
663 - jQuery('.unfix-all-site-security-issues').addClass('disabled');
867 + mainwpVars.bulkTaskRunning = true;
868 + mainwp_managesites_check_abandoned_all_loop_next(which);
869 +};
664 870
665 - jQuery.post(ajaxurl, data, function (pRefresh) {
666 - return function () {
667 - el.show();
668 - if (pRefresh) {
669 - window.location.href = location.href;
670 - }
871 +let mainwp_managesites_check_abandoned_all_loop_next = function (which) {
872 + while (mainwpVars.bulkTaskRunning && (mainwpVars.currentThreads < mainwpVars.maxThreads) && (mainwpVars.websitesLeft > 0)) {
873 + mainwp_managesites_check_abandoned_all_upgrade_next(which);
671 874 }
672 - }(refresh, el), 'json');
673 875 };
876 +let mainwp_managesites_check_abandoned_all_upgrade_next = function (which) {
877 + mainwpVars.currentThreads++;
878 + mainwpVars.websitesLeft--;
674 879
675 -jQuery(document).on('click', '.unfix-all-site-security-issues', function () {
880 + let websiteId = mainwpVars.websitesToUpgrade[mainwpVars.currentWebsite++];
881 + dashboard_update_site_status(websiteId, '<i class="sync alternate loading icon"></i>');
676 882
677 - jQuery('#mainwp-secuirty-issues-loader').show();
883 + mainwp_managesites_check_abandoned_int(websiteId, which);
884 +};
678 885
679 - var data = mainwp_secure_data({
680 - action: 'mainwp_security_issues_unfix',
681 - feature: 'all',
682 - id: jQuery(jQuery(this).parents('.item')[0]).attr('siteid')
683 - });
886 +let mainwp_managesites_check_abandoned_int = function (siteid, which) {
684 887
685 - jQuery(this).hide();
686 - jQuery('.fix-all-site-security-issues').addClass('disabled');
687 - jQuery('.unfix-all-site-security-issues').addClass('disabled');
888 + let data = mainwp_secure_data({
889 + action: 'mainwp_check_abandoned',
890 + siteId: siteid,
891 + which: which
892 + });
688 893
689 - jQuery.post(ajaxurl, data, function () {
690 - window.location.href = location.href;
691 - }, 'json');
692 -});
693 -securityIssues_unfix = function (feature) {
694 - if (jQuery('#' + feature + '_unfix')) {
695 - jQuery('#' + feature + '_unfix').hide();
696 - }
697 - jQuery('#' + feature + '_extra').hide();
698 - jQuery('#' + feature + '_ok').hide();
699 - jQuery('#' + feature + '_nok').hide();
700 - jQuery('#' + feature + '_loading').show();
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 + });
915 +};
701 916
702 - var data = mainwp_secure_data({
703 - action: 'mainwp_security_issues_unfix',
704 - feature: feature,
705 - id: jQuery('#securityIssueSite').val()
706 - });
707 - jQuery.post(ajaxurl, data, function (response) {
708 - securityIssues_handle(response);
709 - }, 'json');
710 -};
711 -securityIssues_request = function (websiteId) {
712 - var data = mainwp_secure_data({
713 - action: 'mainwp_security_issues_request',
714 - id: websiteId
715 - });
716 - jQuery.post(ajaxurl, data, function (response) {
717 - securityIssues_handle(response);
718 - }, 'json');
719 -};
720 -securityIssues_handle = function (response) {
721 - var result = '';
722 - if (response.error) {
723 - result = getErrorMessage(response.error);
724 - } else {
725 - try {
726 - var res = response.result;
727 - for (var issue in res) {
728 - if (jQuery('#' + issue + '_loading')) {
729 - jQuery('#' + issue + '_loading').hide();
730 - if (res[issue] == 'Y') {
731 - jQuery('#' + issue + '_extra').hide();
732 - jQuery('#' + issue + '_nok').hide();
733 - if (jQuery('#' + issue + '_fix')) {
734 - jQuery('#' + issue + '_fix').hide();
917 +/**
918 + * MainWP UI.
919 + */
920 +jQuery(function () {
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);
735 929 }
736 - if (jQuery('#' + issue + '_unfix')) {
737 - jQuery('#' + issue + '_unfix').show();
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);
738 932 }
739 - jQuery('#' + issue + '_ok').show();
740 - jQuery('#' + issue + '-status-ok').show();
741 - jQuery('#' + issue + '-status-nok').hide();
742 - if (issue == 'readme') {
743 - jQuery('#readme-wpe-nok').hide();
744 - }
745 - } else {
746 - jQuery('#' + issue + '_extra').hide();
747 - jQuery('#' + issue + '_ok').hide();
748 - jQuery('#' + issue + '_nok').show();
749 - if (jQuery('#' + issue + '_fix')) {
750 - jQuery('#' + issue + '_fix').show();
751 - }
752 - if (jQuery('#' + issue + '_unfix')) {
753 - jQuery('#' + issue + '_unfix').hide();
754 - }
933 + jQuery('input[name=reset_overview_settings]').attr('value', 1);
934 + jQuery('#submit-overview-settings').click();
935 + }, false, false, true);
936 + return false;
937 + });
938 +});
755 939
756 - if (res[issue] != 'N') {
757 - jQuery('#' + issue + '_extra').html(res[issue]);
758 - jQuery('#' + issue + '_extra').show();
940 +/**
941 + * Sync Sites
942 + */
943 +
944 +jQuery(function () {
945 + jQuery('#mainwp-sync-sites').on('click', function () {
946 + mainwp_sync_sites_data();
947 + });
948 +
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 + });
958 +});
959 +
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());
964 + });
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);
759 973 }
760 - }
974 + });
975 + for (let id of excludeIds) {
976 + dashboard_update_site_hide(id);
761 977 }
762 - }
978 + allWebsiteIds = selectedIds;
979 + globalSync = false;
980 + }
763 981
764 - var unSetFeatures = jQuery('#mainwp-security-issues-table').attr('un-set');
765 - if (unSetFeatures != '') {
766 - unSetFeatures = unSetFeatures.split(',');
767 - if (unSetFeatures.length > 0) {
768 - for (var ival in unSetFeatures) {
769 - issue = unSetFeatures[ival];
770 - console.log(res[issue]);
771 - if (res[issue] == 'Y') {
772 - securityIssues_unfix(issue);
773 - }
774 - }
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 + }
985 +
986 + let nrOfWebsites = allWebsiteIds.length;
987 +
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();
775 996 }
776 - }
997 + });
777 998
778 - } catch (err) {
779 - result = '<i class="exclamation circle icon"></i> ' + __('Undefined error!');
999 + if (jQuery('#mainwp-sync-sites-modal').attr('current-wpid') > 0) {
1000 + globalSync = false;
780 1001 }
781 - }
782 - if (result != '') {
783 - //show error!
784 - }
785 -};
786 1002
787 -updatesoverview_bulk_check_abandoned = function (which) {
788 - if ('plugin' == which) {
789 - confirmMsg = __("You are about to check abandoned plugins on the sites?");
790 - } else {
791 - confirmMsg = __("You are about to check abandoned themes on the sites?");
792 - }
793 - mainwp_confirm(confirmMsg, _callback = function () { mainwp_managesites_bulk_check_abandoned('all', which); });
794 -}
1003 + dashboard_update(allWebsiteIds, globalSync, pAction);
795 1004
796 -mainwp_managesites_bulk_check_abandoned = function (siteIds, which) {
797 - var allWebsiteIds = jQuery('.dashboard_wp_id').map(function (indx, el) {
798 - return jQuery(el).val();
799 - });
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 () {
800 1013
801 - if ('all' == siteIds) {
802 - siteIds = allWebsiteIds;
803 - }
1014 + });
1015 + }
1016 + }
1017 +};
804 1018
805 - var selectedIds = [], excludeIds = [];
806 - if (siteIds instanceof Array) {
807 - jQuery.grep(allWebsiteIds, function (el) {
808 - if (jQuery.inArray(el, siteIds) !== -1) {
809 - selectedIds.push(el);
810 - } else {
811 - excludeIds.push(el);
812 - }
813 - });
814 - for (var i = 0; i < excludeIds.length; i++) {
815 - dashboard_update_site_hide(excludeIds[i]);
816 - }
817 - allWebsiteIds = selectedIds;
818 - //jQuery('#refresh-status-total').text(allWebsiteIds.length);
819 - }
1019 +mainwpVars.websitesToUpdate = [];
1020 +mainwpVars.websitesTotal = 0;
1021 +mainwpVars.websitesLeft = 0;
1022 +mainwpVars.websitesDone = 0;
1023 +mainwpVars.currentWebsite = 0;
1024 +mainwpVars.bulkTaskRunning = false;
1025 +mainwpVars.currentThreads = 0;
1026 +mainwpVars.maxThreads = mainwpParams['maximumSyncRequests'] == undefined ? 8 : mainwpParams['maximumSyncRequests'];
1027 +mainwpVars.maxUpdateThreads = mainwpParams['maximumInstallUpdateRequests'] == undefined ? 3 : mainwpParams['maximumInstallUpdateRequests'];
820 1028
821 - var nrOfWebsites = allWebsiteIds.length;
1029 +let globalSync = true;
822 1030
823 - if (nrOfWebsites == 0)
824 - return false;
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;
825 1038
826 - var siteNames = {};
1039 + mainwpVars.bulkTaskRunning = true;
827 1040
828 - for (var i = 0; i < allWebsiteIds.length; i++) {
829 - dashboard_update_site_status(allWebsiteIds[i], '<i class="clock outline icon"></i>');
830 - siteNames[allWebsiteIds[i]] = jQuery('.sync-site-status[siteid="' + allWebsiteIds[i] + '"]').attr('niceurl');
831 - }
832 - var initData = {
833 - progressMax: nrOfWebsites,
834 - title: 'Check abandoned ' + ('plugin' == which ? 'plugins' : 'themes'),
835 - statusText: __('started'),
836 - callback: function () {
837 - bulkManageSitesTaskRunning = false;
838 - window.location.href = location.href;
1041 + if (mainwpVars.websitesTotal == 0) {
1042 + dashboard_update_done(pAction);
1043 + } else {
1044 + dashboard_loop_next(pAction);
839 1045 }
840 - };
841 - mainwpPopup('#mainwp-sync-sites-modal').init(initData);
842 -
843 - mainwp_managesites_check_abandoned_all_int(allWebsiteIds, which);
844 1046 };
845 1047
846 -mainwp_managesites_check_abandoned_all_int = function (websiteIds, which) {
847 - websitesToUpgrade = websiteIds;
848 - currentWebsite = 0;
849 - websitesDone = 0;
850 - websitesTotal = websitesLeft = websitesToUpgrade.length;
1048 +(function () {
1049 + // Create global namespace
1050 + const sync = globalThis.dashboardSync = globalThis.dashboardSync || {
1051 + container: null,
1052 + statusMap: new Map(),
1053 + rowMap: new Map(),
851 1054
852 - bulkTaskRunning = true;
853 - mainwp_managesites_check_abandoned_all_loop_next(which);
854 -};
1055 + data: new Map(),
1056 + queue: [],
855 1057
856 -mainwp_managesites_check_abandoned_all_loop_next = function (which) {
857 - while (bulkTaskRunning && (currentThreads < maxThreads) && (websitesLeft > 0)) {
858 - mainwp_managesites_check_abandoned_all_upgrade_next(which);
859 - }
860 -};
861 -mainwp_managesites_check_abandoned_all_upgrade_next = function (which) {
862 - currentThreads++;
863 - websitesLeft--;
1058 + scheduled: false,
1059 + initialized: false,
864 1060
865 - var websiteId = websitesToUpgrade[currentWebsite++];
866 - dashboard_update_site_status(websiteId, '<i class="sync alternate loading icon"></i>');
1061 + BATCH_SIZE: 50
1062 + };
867 1063
868 - mainwp_managesites_check_abandoned_int(websiteId, which);
869 -};
1064 + // -----------------------------
1065 + // INIT CACHE
1066 + // -----------------------------
1067 + function init() {
1068 + if (sync.initialized) return;
870 1069
871 -mainwp_managesites_check_abandoned_int = function (siteid, which) {
1070 + sync.container = document.getElementById('sync-sites-status');
1071 + if (!sync.container) return;
872 1072
873 - var data = mainwp_secure_data({
874 - action: 'mainwp_check_abandoned',
875 - siteId: siteid,
876 - which: which
877 - });
1073 + const nodes = sync.container.querySelectorAll('.sync-site-status');
878 1074
879 - jQuery.ajax({
880 - type: 'POST',
881 - url: ajaxurl,
882 - data: data,
883 - success: function (pSiteid) {
884 - return function (response) {
885 - currentThreads--;
886 - websitesDone++;
887 - mainwpPopup('#mainwp-sync-sites-modal').setProgressSite(websitesDone);
888 - if (response.error != undefined) {
889 - dashboard_update_site_status(pSiteid, '<i class="red times icon"></i>');
890 - } else if (response.result && response.result == 'success') {
891 - dashboard_update_site_status(pSiteid, '<i class="green check icon"></i>', true);
892 - } else {
893 - dashboard_update_site_status(pSiteid, '<i class="red times icon"></i>');
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'));
894 1079 }
895 - mainwp_managesites_check_abandoned_all_loop_next(which);
896 - }
897 - }(siteid),
898 - dataType: 'json'
899 - });
900 - return false;
901 -};
902 1080
903 -/**
904 - * MainWP UI.
905 - */
906 -jQuery(function () {
907 - jQuery('#reset-overview-settings').on('click', function () {
908 - mainwp_confirm(__('Are you sure.'), function () {
909 - var which_set = jQuery('input[name=reset_overview_which_settings]').val();
910 - if ('sidebar_settings' == which_set) {
911 - jQuery('#mainwp_sidebarPosition').dropdown('set selected', 1);
912 - } else if ('overview_settings' == which_set) {
913 - jQuery('input[name=hide_update_everything]').prop('checked', false);
914 - jQuery('.mainwp_hide_wpmenu_checkboxes input[name="mainwp_show_widgets[]"]').prop('checked', true);
915 - }
916 - 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) {
917 - jQuery('input[name="mainwp_show_columns[]"]').prop('checked', true);
918 - }
919 - jQuery('input[name=reset_overview_settings]').attr('value', 1);
920 - jQuery('#submit-overview-settings').click();
921 - }, false, false, true);
922 - return false;
923 - });
924 -});
1081 + sync.initialized = true;
1082 + }
925 1083
926 -/**
927 - * Sync Sites
928 - */
1084 + // Ensure DOM ready
1085 + if (document.readyState === 'loading') {
1086 + document.addEventListener('DOMContentLoaded', init);
1087 + } else {
1088 + init();
1089 + }
929 1090
930 -jQuery(document).ready(function () {
931 - jQuery('#mainwp-sync-sites').on('click', function () {
932 - mainwp_sync_sites_data();
933 - });
1091 + // -----------------------------
1092 + // PUBLIC API
1093 + // -----------------------------
1094 + globalThis.dashboard_update_site_status = function (siteId, newStatus, isSuccess) {
1095 + if (!sync.initialized) return;
934 1096
935 - // to compatible with extensions
936 - jQuery('#dashboard_refresh').on('click', function () {
937 - mainwp_sync_sites_data();
938 - });
939 - jQuery('.mainwp-sync-this-site').on('click', function () {
940 - var syncSiteIds = [];
941 - syncSiteIds.push(jQuery(this).attr('site-id'));
942 - mainwp_sync_sites_data(syncSiteIds);
943 - });
944 -});
1097 + sync.data.set(siteId, {
1098 + status: newStatus,
1099 + success: isSuccess
1100 + });
945 1101
946 -mainwp_sync_sites_data = function (syncSiteIds, pAction) {
947 - var allWebsiteIds = jQuery('.dashboard_wp_id').map(function (indx, el) {
948 - return jQuery(el).val();
949 - });
950 - var globalSync = true;
951 - var selectedIds = [], excludeIds = [];
952 - if (syncSiteIds instanceof Array) {
953 - jQuery.grep(allWebsiteIds, function (el) {
954 - if (jQuery.inArray(el, syncSiteIds) !== -1) {
955 - selectedIds.push(el);
956 - } else {
957 - excludeIds.push(el);
958 - }
959 - });
960 - for (var i = 0; i < excludeIds.length; i++) {
961 - dashboard_update_site_hide(excludeIds[i]);
962 - }
963 - allWebsiteIds = selectedIds;
964 - globalSync = false;
965 - }
1102 + sync.queue.push(siteId);
966 1103
967 - for (var i = 0; i < allWebsiteIds.length; i++) {
968 - dashboard_update_site_status(allWebsiteIds[i], '<span data-inverted="" data-position="left center" data-tooltip="' + __('Pending', 'mainwp') + '"><i class="clock outline icon"></i></span>');
969 - }
1104 + // ✅ increment success count ONCE
1105 + if (isSuccess) {
1106 + mainwpVars.successCount = (mainwpVars.successCount || 0) + 1;
1107 + }
970 1108
971 - var nrOfWebsites = allWebsiteIds.length;
1109 + if (!sync.scheduled) {
1110 + sync.scheduled = true;
1111 + requestAnimationFrame(processQueue);
1112 + }
1113 + };
972 1114
973 - mainwpPopup('#mainwp-sync-sites-modal').init({
974 - title: (pAction == 'checknow' ? __('Check Now') : __('Data Synchronization')),
975 - progressMax: nrOfWebsites,
976 - statusText: (pAction == 'checknow' ? 'checked' : 'synced'),
977 - callback: function () {
978 - bulkTaskRunning = false;
979 - history.pushState("", document.title, window.location.pathname + window.location.search); // to fix issue for url with hash
980 - window.location.href = location.href;
981 - }
982 - });
1115 + globalThis.dashboard_update_site_hide = function (siteId) {
1116 + const sync = globalThis.dashboardSync;
1117 + if (!sync?.initialized) return;
983 1118
984 - if (jQuery('#mainwp-sync-sites-modal').attr('current-wpid') > 0) {
985 - globalSync = false;
986 - }
1119 + const rowEl = sync.rowMap.get(siteId);
1120 + if (!rowEl) return;
987 1121
988 - dashboard_update(allWebsiteIds, globalSync, pAction);
1122 + rowEl.style.display = 'none';
1123 + };
989 1124
990 - if (pAction != 'checknow') {
991 - if (nrOfWebsites > 0) {
992 - var data = {
993 - action: 'mainwp_status_saving',
994 - status: 'last_sync_sites',
995 - isGlobalSync: globalSync ? 1 : 0
996 - };
997 - jQuery.post(ajaxurl, mainwp_secure_data(data), function () {
1125 + // -----------------------------
1126 + // PROCESS QUEUE (BATCHED)
1127 + // -----------------------------
1128 + function processQueue() {
1129 + sync.scheduled = false;
998 1130
999 - });
1000 - }
1001 - }
1002 -};
1131 + let count = 0;
1003 1132
1004 -var websitesToUpdate = [];
1005 -var websitesTotal = 0;
1006 -var websitesLeft = 0;
1007 -var websitesDone = 0;
1008 -var currentWebsite = 0;
1009 -var bulkTaskRunning = false;
1010 -var currentThreads = 0;
1011 -var maxThreads = mainwpParams['maximumSyncRequests'] == undefined ? 8 : mainwpParams['maximumSyncRequests'];
1012 -var globalSync = true;
1133 + while (sync.queue.length && count < sync.BATCH_SIZE) {
1134 + const siteId = sync.queue.shift();
1135 + const data = sync.data.get(siteId);
1013 1136
1014 -dashboard_update = function (websiteIds, isGlobalSync, pAction) {
1015 - websitesToUpdate = websiteIds;
1016 - currentWebsite = 0;
1017 - websitesDone = 0;
1018 - websitesTotal = websitesLeft = websitesToUpdate.length;
1019 - globalSync = isGlobalSync;
1137 + const statusEl = sync.statusMap.get(siteId);
1138 + const rowEl = sync.rowMap.get(siteId);
1020 1139
1021 - bulkTaskRunning = true;
1140 + if (!statusEl || !rowEl) continue;
1022 1141
1023 - if (websitesTotal == 0) {
1024 - dashboard_update_done(pAction);
1025 - } else {
1026 - dashboard_loop_next(pAction);
1027 - }
1028 -};
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 + }
1029 1147
1030 -dashboard_update_site_status = function (siteId, newStatus, isSuccess) {
1031 - jQuery('.sync-site-status[siteid="' + siteId + '"]').html(newStatus);
1032 - // Move successfully synced site to the bottom of the sync list
1033 - if (typeof isSuccess !== 'undefined' && isSuccess) {
1034 - var row = jQuery('.sync-site-status[siteid="' + siteId + '"]').closest('.item');
1035 - jQuery(row).insertAfter(jQuery("#sync-sites-status .item").not('.disconnected-site').last());
1036 - }
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 + }
1037 1170 };
1038 1171
1039 -dashboard_update_site_hide = function (siteId) {
1040 - 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();
1041 1174 };
1042 1175
1043 -dashboard_loop_next = function (pAction) {
1044 - while (bulkTaskRunning && (currentThreads < maxThreads) && (websitesLeft > 0)) {
1045 - dashboard_update_next(pAction);
1046 - }
1176 +let dashboard_loop_next = function (pAction) {
1177 + while (mainwpVars.bulkTaskRunning && (mainwpVars.currentThreads < mainwpVars.maxThreads) && (mainwpVars.websitesLeft > 0)) {
1178 + dashboard_update_next(pAction);
1179 + }
1047 1180 };
1048 1181
1049 -dashboard_update_done = function (pAction) {
1050 - currentThreads--;
1051 - if (!bulkTaskRunning)
1052 - return;
1053 - websitesDone++;
1054 - if (websitesDone > websitesTotal)
1055 - websitesDone = websitesTotal;
1182 +let dashboard_update_done = function (pAction) {
1183 + mainwpVars.currentThreads--;
1056 1184
1057 - mainwpPopup('#mainwp-sync-sites-modal').setProgressSite(websitesDone);
1185 + if (!mainwpVars.bulkTaskRunning) return;
1058 1186
1059 - if (websitesDone == websitesTotal) {
1060 - var successSites = jQuery('#mainwp-sync-sites-modal .check.green.icon').length;
1061 - if (websitesDone == successSites) {
1062 - bulkTaskRunning = false;
1063 - setTimeout(function () {
1064 - mainwpPopup('#mainwp-sync-sites-modal').close(true);
1065 - }, 3000);
1066 - } else {
1067 - bulkTaskRunning = false;
1187 + mainwpVars.websitesDone++;
1188 + if (mainwpVars.websitesDone > mainwpVars.websitesTotal) {
1189 + mainwpVars.websitesDone = mainwpVars.websitesTotal;
1068 1190 }
1069 - return;
1070 - }
1071 1191
1072 - dashboard_loop_next(pAction);
1073 -};
1192 + // ✅ Cache popup instance (avoid re-query)
1193 + const popup = mainwpVars._popup || (
1194 + mainwpVars._popup = mainwpPopup('#mainwp-sync-sites-modal')
1195 + );
1074 1196
1075 -dashboard_update_next = function (pAction) {
1076 - currentThreads++;
1077 - websitesLeft--;
1078 - var websiteId = websitesToUpdate[currentWebsite++];
1079 - dashboard_update_site_status(websiteId, '<span data-inverted="" data-position="left center" data-tooltip="' + __('Syncing...', 'mainwp') + '"><i class="sync alternate loading icon"></i></span>');
1080 - var data = mainwp_secure_data({
1081 - action: ('checknow' == pAction ? 'mainwp_checksites' : 'mainwp_syncsites'),
1082 - wp_id: websiteId,
1083 - isGlobalSync: globalSync
1084 - });
1197 + popup.setProgressSite(mainwpVars.websitesDone);
1085 1198
1199 + // ✅ Avoid DOM query for success count → track in JS
1200 + if (mainwpVars.websitesDone === mainwpVars.websitesTotal) {
1086 1201
1202 + const successSites = mainwpVars.successCount || 0;
1087 1203
1088 - 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);
1089 1214 };
1090 1215
1091 -dashboard_update_next_int = function (websiteId, data, errors, action) {
1092 - jQuery.ajax({
1093 - type: 'POST',
1094 - url: ajaxurl,
1095 - data: data,
1096 - success: function (pWebsiteId, pAction) {
1097 - return function (response) {
1098 - if (response.error) {
1099 - var extErr = response.error;
1100 - 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);
1101 1233 } else {
1102 - 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;
1103 1235 }
1104 - dashboard_update_done(pAction);
1105 - }
1106 - }(websiteId, action),
1107 - error: function (pWebsiteId, pData, pErrors, pAction) {
1108 - return function () {
1109 - if (pErrors > 5) {
1110 - 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>');
1111 - dashboard_update_done(pAction);
1112 - } else {
1113 - pErrors++;
1114 - dashboard_update_next_int(pWebsiteId, pData, pErrors, pAction);
1115 - }
1116 - }
1117 - }(websiteId, data, errors, action),
1118 - dataType: 'json'
1119 - });
1236 + return;
1237 + }
1238 +
1239 + dashboard_loop_next(pAction);
1120 1240 };
1121 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 + }
1122 1251
1123 -/**
1124 - * Delete nonmainwp actions.
1125 - */
1126 -mainwp_delete_nonmainwp_data_start = function (syncSiteIds) {
1127 - var allWebsiteIds = jQuery('.dashboard_wp_id').map(function (indx, el) {
1128 - return jQuery(el).val();
1129 - });
1130 - var selectedIds = [], excludeIds = [];
1131 - if (syncSiteIds instanceof Array) {
1132 - jQuery.grep(allWebsiteIds, function (el) {
1133 - if (jQuery.inArray(el, syncSiteIds) !== -1) {
1134 - selectedIds.push(el);
1135 - } else {
1136 - excludeIds.push(el);
1137 - }
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
1138 1257 });
1139 - for (var i = 0; i < excludeIds.length; i++) {
1140 - dashboard_update_site_hide(excludeIds[i]);
1141 - }
1142 - allWebsiteIds = selectedIds;
1143 - }
1144 1258
1145 - for (var i = 0; i < allWebsiteIds.length; i++) {
1146 - dashboard_update_site_status(allWebsiteIds[i], '<span data-inverted="" data-position="left center" data-tooltip="' + __('Pending', 'mainwp') + '"><i class="clock outline icon"></i></span>');
1147 - }
1148 1259
1149 - var nrOfWebsites = allWebsiteIds.length;
1150 1260
1151 - mainwpPopup('#mainwp-sync-sites-modal').init({
1152 - title: __('Delete Non-MainWP Changes'),
1153 - progressMax: nrOfWebsites,
1154 - statusText: 'deleted',
1155 - callback: function () {
1156 - bulkTaskRunning = false;
1157 - history.pushState("", document.title, window.location.pathname + window.location.search); // to fix issue for url with hash
1158 - window.location.href = location.href;
1159 - }
1160 - });
1161 - mainwp_delete_nonmainwp_data_start_next(allWebsiteIds);
1261 + dashboard_update_next_int(websiteId, data, 0, pAction);
1162 1262 };
1163 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 +};
1164 1294
1165 -mainwp_delete_nonmainwp_data_start_next = function (websiteIds) {
1166 - websitesToUpdate = websiteIds;
1167 - currentWebsite = 0;
1168 - websitesDone = 0;
1169 - websitesTotal = websitesLeft = websitesToUpdate.length;
1170 1295
1171 - bulkTaskRunning = true;
1296 +/**
1297 + * Delete site changes actions.
1298 + */
1172 1299
1173 - if (websitesTotal == 0) {
1174 - mainwp_delete_nonmainwp_data_done();
1175 - } else {
1176 - mainwp_delete_nonmainwp_data_loop_next();
1177 - }
1178 -};
1300 +let mainwp_delete_nonmainwp_data_start = function () {
1301 + mainwp_delete_nonmainwp_data_start_next();
1302 +}
1179 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 +}
1180 1309
1181 -mainwp_delete_nonmainwp_data_loop_next = function () {
1182 - while (bulkTaskRunning && (currentThreads < maxThreads) && (websitesLeft > 0)) {
1183 - mainwp_delete_nonmainwp_data_next();
1184 - }
1310 +let mainwp_delete_nonmainwp_data_next = function () {
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);
1185 1320 };
1186 1321
1187 -mainwp_delete_nonmainwp_data_next = function () {
1188 - currentThreads++;
1189 - websitesLeft--;
1190 - var websiteId = websitesToUpdate[currentWebsite++];
1191 - dashboard_update_site_status(websiteId, '<span data-inverted="" data-position="left center" data-tooltip="' + __('Deleting...', 'mainwp') + '"><i class="sync alternate loading icon"></i></span>');
1192 - var data = mainwp_secure_data({
1193 - action: 'mainwp_delete_non_mainwp_actions',
1194 - wp_id: websiteId,
1195 - });
1196 - mainwp_delete_nonmainwp_data_next_int(websiteId, data, 0);
1322 +let mainwp_delete_nonmainwp_data_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 + 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 + });
1197 1351 };
1198 1352
1199 -mainwp_delete_nonmainwp_data_next_int = function (websiteId, data, errors) {
1200 - jQuery.ajax({
1201 - type: 'POST',
1202 - url: ajaxurl,
1203 - data: data,
1204 - success: function (pWebsiteId) {
1205 - return function (response) {
1206 - if (response.error) {
1207 - var extErr = response.error;
1208 - dashboard_update_site_status(pWebsiteId, '<span data-inverted="" data-position="left center" data-tooltip="' + extErr + '"><i class="exclamation red icon"></i></span>');
1209 - } else {
1210 - 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);
1211 - }
1212 - mainwp_delete_nonmainwp_data_done();
1213 - }
1214 - }(websiteId),
1215 - error: function (pWebsiteId, pData, pErrors) {
1216 - return function () {
1217 - if (pErrors > 5) {
1218 - 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>');
1219 - mainwp_delete_nonmainwp_data_done();
1220 - } else {
1221 - pErrors++;
1222 - mainwp_delete_nonmainwp_data_next_int(pWebsiteId, pData, pErrors);
1223 - }
1224 - }
1225 - }(websiteId, data, errors),
1226 - dataType: 'json'
1227 - });
1228 -};
1229 1353
1354 +let mainwp_delete_nonmainwp_data_done = function () {
1355 + mainwpVars.currentThreads--;
1356 + if (!mainwpVars.bulkTaskRunning)
1357 + return;
1358 + mainwpVars.websitesDone++;
1359 + if (mainwpVars.websitesDone > mainwpVars.websitesTotal)
1360 + mainwpVars.websitesDone = mainwpVars.websitesTotal;
1230 1361
1231 -mainwp_delete_nonmainwp_data_done = function () {
1232 - currentThreads--;
1233 - if (!bulkTaskRunning)
1234 - return;
1235 - websitesDone++;
1236 - if (websitesDone > websitesTotal)
1237 - websitesDone = websitesTotal;
1362 + mainwpPopup('#mainwp-sync-sites-modal').setProgressSite(mainwpVars.websitesDone);
1238 1363
1239 - mainwpPopup('#mainwp-sync-sites-modal').setProgressSite(websitesDone);
1240 -
1241 - if (websitesDone == websitesTotal) {
1242 - jQuery("#mainwp-non-mainwp-changes-table tbody").fadeOut("slow");
1243 - var successSites = jQuery('#mainwp-sync-sites-modal .check.green.icon').length;
1244 - if (websitesDone == successSites) {
1245 - bulkTaskRunning = false;
1246 - setTimeout(function () {
1247 - mainwpPopup('#mainwp-sync-sites-modal').close(true);
1248 - }, 3000);
1249 - } else {
1250 - 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;
1251 1376 }
1252 - return;
1253 - }
1254 - mainwp_delete_nonmainwp_data_loop_next();
1377 + mainwp_delete_nonmainwp_data_loop_next();
1255 1378 };
1256 1379
1257 1380
1258 -mainwp_tool_disconnect_sites = function () {
1381 +let mainwp_tool_disconnect_sites = function () {
1259 1382
1260 - 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 () {
1261 - var allWebsiteIds = jQuery('.dashboard_wp_id').map(function (indx, el) {
1262 - return jQuery(el).val();
1263 - });
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 + });
1264 1387
1265 - for (var i = 0; i < allWebsiteIds.length; i++) {
1266 - dashboard_update_site_status(allWebsiteIds[i], '<i class="clock outline icon"></i>');
1267 - }
1388 + for (let id of allWebsiteIds) {
1389 + dashboard_update_site_status(id, '<i class="clock outline icon"></i>');
1390 + }
1268 1391
1269 - var nrOfWebsites = allWebsiteIds.length;
1392 + let nrOfWebsites = allWebsiteIds.length;
1270 1393
1271 - mainwpPopup('#mainwp-sync-sites-modal').init({
1272 - title: __('Disconnect All Sites'),
1273 - progressMax: nrOfWebsites,
1274 - statusText: __('disconnected'),
1275 - callback: function () {
1276 - window.location.href = location.href;
1277 - }
1278 - });
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 + });
1279 1402
1280 - websitesToUpdate = allWebsiteIds;
1281 - currentWebsite = 0;
1282 - websitesDone = 0;
1283 - websitesTotal = websitesLeft = websitesToUpdate.length;
1403 + mainwpVars.websitesToUpdate = allWebsiteIds;
1404 + mainwpVars.currentWebsite = 0;
1405 + mainwpVars.websitesDone = 0;
1406 + mainwpVars.websitesTotal = mainwpVars.websitesLeft = mainwpVars.websitesToUpdate.length;
1284 1407
1285 - bulkTaskRunning = true;
1408 + mainwpVars.bulkTaskRunning = true;
1286 1409
1287 - if (websitesTotal == 0) {
1288 - mainwp_tool_disconnect_sites_done();
1289 - } else {
1290 - mainwp_tool_disconnect_sites_loop_next();
1291 - }
1292 - }, 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');
1293 1416 };
1294 1417
1295 -mainwp_tool_disconnect_sites_done = function () {
1296 - currentThreads--;
1297 - if (!bulkTaskRunning)
1298 - return;
1299 - websitesDone++;
1300 - if (websitesDone > websitesTotal)
1301 - websitesDone = websitesTotal;
1418 +let mainwp_tool_disconnect_sites_done = function () {
1419 + mainwpVars.currentThreads--;
1420 + if (!mainwpVars.bulkTaskRunning)
1421 + return;
1422 + mainwpVars.websitesDone++;
1423 + if (mainwpVars.websitesDone > mainwpVars.websitesTotal)
1424 + mainwpVars.websitesDone = mainwpVars.websitesTotal;
1302 1425
1303 - mainwpPopup('#mainwp-sync-sites-modal').setProgressSite(websitesDone);
1426 + mainwpPopup('#mainwp-sync-sites-modal').setProgressSite(mainwpVars.websitesDone);
1304 1427
1305 - mainwp_tool_disconnect_sites_loop_next();
1428 + mainwp_tool_disconnect_sites_loop_next();
1306 1429 };
1307 1430
1308 -mainwp_tool_disconnect_sites_loop_next = function () {
1309 - while (bulkTaskRunning && (currentThreads < maxThreads) && (websitesLeft > 0)) {
1310 - mainwp_tool_disconnect_sites_next();
1311 - }
1431 +let mainwp_tool_disconnect_sites_loop_next = function () {
1432 + while (mainwpVars.bulkTaskRunning && (mainwpVars.currentThreads < mainwpVars.maxThreads) && (mainwpVars.websitesLeft > 0)) { // NOSONAR - vars modified outside function.
1433 + mainwp_tool_disconnect_sites_next();
1434 + }
1312 1435 };
1313 1436
1314 -mainwp_tool_disconnect_sites_next = function () {
1315 - currentThreads++;
1316 - websitesLeft--;
1317 - var websiteId = websitesToUpdate[currentWebsite++];
1318 - dashboard_update_site_status(websiteId, '<i class="sync alternate loading icon"></i>');
1319 - var data = mainwp_secure_data({
1320 - action: 'mainwp_disconnect_site',
1321 - wp_id: websiteId
1322 - });
1323 - mainwp_tool_disconnect_sites_next_int(websiteId, data, 0);
1437 +let mainwp_tool_disconnect_sites_next = function () {
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);
1324 1447 };
1325 1448
1326 -mainwp_tool_disconnect_sites_next_int = function (websiteId, data, errors) {
1327 - jQuery.ajax({
1328 - type: 'POST',
1329 - url: ajaxurl,
1330 - data: data,
1331 - success: function (pWebsiteId) {
1332 - return function (response) {
1333 - if (response && response.error) {
1334 - dashboard_update_site_status(pWebsiteId, response.error + '<i class="exclamation red icon"></i>');
1335 - } else if (response && response.result == 'success') {
1336 - dashboard_update_site_status(websiteId, '<i class="check green icon"></i>', true);
1337 - } else {
1338 - dashboard_update_site_status(pWebsiteId, __('Undefined error!') + ' <i class="exclamation red icon"></i>');
1339 - }
1340 - mainwp_tool_disconnect_sites_done();
1341 - }
1342 - }(websiteId),
1343 - error: function (pWebsiteId, pData, pErrors) {
1344 - return function () {
1345 - if (pErrors > 5) {
1346 - 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>');
1347 - mainwp_tool_disconnect_sites_done();
1348 - } else {
1349 - pErrors++;
1350 - mainwp_tool_disconnect_sites_next_int(pWebsiteId, pData, pErrors);
1351 - }
1352 - }
1353 - }(websiteId, data, errors),
1354 - dataType: 'json'
1355 - });
1449 +let mainwp_tool_disconnect_sites_next_int = function (websiteId, data, errors) {
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 + });
1356 1479 };
1357 1480
1358 -mainwp_tool_clear_activation_data = function (pObj) {
1359 - var loc = jQuery(pObj).attr('href');
1360 - mainwp_confirm('Are you sure?', function () {
1361 - window.location = loc;
1362 - });
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 + });
1363 1486 };
1364 1487
1488 +
1365 1489 /**
1366 1490 * Manage sites page
1367 1491 */
1368 1492
1369 -jQuery(document).ready(function ($) {
1370 - jQuery('#mainwp-backup-type').on('change', function () {
1371 - if (jQuery(this).val() == 'full')
1372 - jQuery('.mainwp-backup-full-exclude').show();
1373 - else
1374 - jQuery('.mainwp-backup-full-exclude').hide();
1375 - });
1376 - jQuery('.mainwp-checkbox-showhide-elements').on('click', function () {
1377 - var hiel = $(this).attr('hide-parent');
1378 - mainwp_showhide_elements(hiel, $(this).find('input').is(':checked'));
1379 - });
1493 +jQuery(function ($) {
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 + });
1380 1516
1381 - jQuery('.mainwp-selecter-showhide-elements').on('change', function () {
1382 - var hiel = $(this).attr('hide-parent');
1383 - var hival = $(this).attr('hide-value');
1384 - hival = hival.split('-'); // support multi hide values.
1385 - var selectedval = $(this).val();
1386 - mainwp_showhide_elements(hiel, hival.includes(selectedval));
1387 - });
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 + });
1388 1524 });
1389 1525
1390 1526 function mainwp_showhide_elements(attEl, valHi) {
1391 - if (valHi) {
1392 - jQuery('[hide-element=' + attEl + ']').fadeOut(300);
1393 - } else {
1394 - jQuery('[hide-element=' + attEl + ']').fadeIn(200);
1395 - }
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 + }
1396 1539 }
1397 1540
1398 1541
1399 -jQuery(document).ready(function ($) {
1400 - $('#mainwp_settings_verify_connection_method').on('change', function () {
1401 - var selectedval = $(this).val();
1402 - var selectedval = $(this).val();
1403 - if (selectedval == 2) { // phpseclib.
1404 - $('.mainwp-hide-elemenent-sign-algo').fadeOut(200);
1405 - } else {
1406 - $('.mainwp-hide-elemenent-sign-algo').fadeIn(200);
1407 - }
1408 - });
1542 +jQuery(function ($) {
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 + });
1409 1551
1410 - $('#mainwp_managesites_edit_verify_connection_method').on('change', function () {
1411 - var selectedval = $(this).val();
1412 - if (selectedval == 2 || selectedval == 3) { // phpseclib.
1413 - $('.mainwp-hide-elemenent-sign-algo').fadeOut(200);
1414 - } else {
1415 - $('.mainwp-hide-elemenent-sign-algo').fadeIn(200);
1416 - }
1417 - });
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 + });
1418 1560
1419 1561
1420 - $('#mainwp_managesites_edit_openssl_alg').on('change', function () {
1421 - var selectedval = $(this).val();
1422 - if (selectedval == 1) {
1423 - $('.mainwp-hide-elemenent-sign-algo-note').fadeIn(200);
1424 - } else {
1425 - $('.mainwp-hide-elemenent-sign-algo-note').fadeOut(200);
1426 - }
1427 - });
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 + });
1428 1570
1429 - $('#mainwp_settings_openssl_alg').on('change', function () {
1430 - var selectedval = $(this).val();
1431 - if (selectedval == 1) {
1432 - $('.mainwp-hide-elemenent-sign-algo-note').fadeIn(200);
1433 - } else {
1434 - $('.mainwp-hide-elemenent-sign-algo-note').fadeOut(200);
1435 - }
1436 - });
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 + });
1437 1579
1438 1580 })
1439 1581
1440 -jQuery(document).ready(function () {
1441 - jQuery(document).on('change', '#mainwp_managesites_add_wpurl', function () {
1442 - var url = jQuery('#mainwp_managesites_add_wpurl').val().trim();
1443 - var protocol = jQuery('#mainwp_managesites_add_wpurl_protocol').val();
1582 +jQuery(function () {
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();
1444 1586
1445 - if (url.lastIndexOf('http://') === 0) {
1446 - protocol = 'http';
1447 - url = url.substring(7);
1448 - } else if (url.lastIndexOf('https://') === 0) {
1449 - protocol = 'https';
1450 - url = url.substring(8);
1451 - }
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 + }
1452 1594
1453 - if (jQuery('#mainwp_managesites_add_wpname').val() == '') {
1454 - jQuery('#mainwp_managesites_add_wpname').val(url);
1455 - }
1456 - jQuery('#mainwp_managesites_add_wpurl').val(url);
1457 - jQuery('#mainwp_managesites_add_wpurl_protocol').val(protocol).trigger("change");
1458 - });
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 + });
1459 1601
1460 - // Trigger the single site reconnect process
1461 - jQuery('.mainwp-manage-wpsites-table').on('click', '.mainwp_site_reconnect', function () {
1462 - mainwp_managesites_reconnect(jQuery(this));
1463 - return false;
1464 - });
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 + });
1465 1607
1466 - jQuery('#mainwp-sites-previews').on('click', '.mainwp_site_card_reconnect', function () {
1467 - mainwp_managesites_cards_reconnect(jQuery(this));
1468 - return false;
1469 - });
1608 + jQuery('#mainwp-sites-previews').on('click', '.mainwp_site_card_reconnect', function () {
1609 + mainwp_managesites_cards_reconnect(jQuery(this));
1610 + return false;
1611 + });
1470 1612
1471 - jQuery('.mainwp-updates-overview-reconnect-site').on('click', function () {
1472 - mainwp_site_overview_reconnect(jQuery(this));
1473 - return false;
1474 - });
1613 + jQuery(document).on('click', '.mainwp-updates-overview-reconnect-site', function () {
1614 + mainwp_site_overview_reconnect(jQuery(this));
1615 + return false;
1616 + });
1475 1617
1476 - jQuery(".chk-sync-install-plugin").on('change', function () {
1477 - var parent = jQuery(this).closest('.sync-ext-row');
1478 - var opts = parent.find(".sync-options input[type='checkbox']");
1479 - if (jQuery(this).is(':checked')) {
1480 - //opts.prop("disabled", false);
1481 - opts.prop("checked", true);
1482 - } else {
1483 - opts.prop("checked", false);
1484 - ///opts.attr( "disabled", "disabled" );
1485 - }
1486 - });
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 + });
1487 1628
1488 - managesites_init();
1629 + managesites_init();
1489 1630 });
1490 1631
1491 1632 jQuery(document).on('change', '#mainwp_managesites_verify_installed_child', function () {
1492 - if (jQuery(this).is(':checked')) {
1493 - jQuery('#mainwp_message_verify_installed_child').hide();
1494 - }
1633 + if (jQuery(this).is(':checked')) {
1634 + jQuery('#mainwp_message_verify_installed_child').hide();
1635 + }
1495 1636 });
1496 1637
1497 -managesites_init = function () {
1498 - jQuery('#mainwp-message-zone').hide();
1499 - jQuery('.sync-ext-row span.status').html('');
1500 - 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');
1501 1642 };
1502 1643
1503 -mainwp_site_overview_reconnect = function (pElement) {
1504 - feedback('mainwp-message-zone', '<i class="notched circle loading icon"></i> ' + 'Trying to reconnect. Please wait...', '');
1505 - var data = mainwp_secure_data({
1506 - action: 'mainwp_reconnectwp',
1507 - siteid: pElement.attr('siteid')
1508 - });
1644 +let mainwp_site_overview_reconnect = function (pElement) {
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 + });
1509 1650
1510 - jQuery.post(ajaxurl, data, function () {
1511 - return function (response) {
1512 - response = response.trim();
1513 - if (response.substr(0, 5) == 'ERROR') {
1514 - var error;
1515 - if (response.length == 5) {
1516 - 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>.';
1517 - 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');
1518 1730 } else {
1519 - error = response.substr(6);
1520 - var err = mainwp_js_get_error_not_detected_connect(error, 'html_msg', 'mainwp-message-zone');
1521 - if (false === err) {
1522 - feedback('mainwp-message-zone', error, 'red'); // it is not json error string.
1523 - }
1731 + mainwp_set_message_zone('#mainwp-message-zone-reconnect', response, 'green');
1732 + mainwp_forceReload();
1524 1733 }
1525 - } else {
1526 - location.reload();
1527 - }
1528 - }
1529 - }());
1734 + });
1530 1735 };
1531 1736
1532 -mainwp_managesites_reconnect = function (pElement) {
1533 - var wrapElement = pElement.closest('tr');
1534 - wrapElement.html('<td colspan="999"><i class="notched circle loading icon"></i> ' + 'Trying to reconnect. Please wait...' + '</td>');
1535 - var data = mainwp_secure_data({
1536 - action: 'mainwp_reconnectwp',
1537 - siteid: wrapElement.attr('siteid')
1538 - });
1539 1737
1540 - jQuery.post(ajaxurl, data, function (pWrapElement) {
1541 - return function (response) {
1542 - response = response.trim();
1543 - pWrapElement.hide(); // hide reconnect item
1544 - if (response.substr(0, 5) == 'ERROR') {
1545 - var error;
1546 - if (response.length == 5) {
1547 - 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>.';
1548 - feedback('mainwp-message-zone', error, 'red');
1549 - } else {
1550 - error = response.substr(6);
1551 - var err = mainwp_js_get_error_not_detected_connect(error, 'html_msg', 'mainwp-message-zone');
1552 - if (false === err) {
1553 - feedback('mainwp-message-zone', error, 'red'); // it is not json error string.
1554 - }
1738 +let mainwp_managesites_reconnect = function (pElement) {
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 + });
1746 +
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);
1555 1771 }
1556 - } else {
1557 - feedback('mainwp-message-zone', response, 'green');
1558 - }
1559 - setTimeout(function () {
1560 - window.location.reload()
1561 - }, 6000);
1562 - }
1563 1772
1564 - }(wrapElement));
1773 + }(wrapElement));
1565 1774 };
1566 1775
1567 -mainwp_managesites_cards_reconnect = function (element) {
1568 - element.html('<i class="notched loading circle icon"></i> Reconnecting...');
1569 - var data = mainwp_secure_data({
1570 - action: 'mainwp_reconnectwp',
1571 - siteid: element.attr('site-id')
1572 - });
1776 +let mainwp_managesites_cards_reconnect = function (element) {
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 + });
1573 1783
1574 - jQuery.post(ajaxurl, data, function (element) {
1575 - return function (response) {
1576 - response = response.trim();
1577 - element.hide();
1578 - if (response.substr(0, 5) == 'ERROR') {
1579 - var error;
1580 - if (response.length == 5) {
1581 - 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>.';
1582 - feedback('mainwp-message-zone', error, 'red');
1583 - } else {
1584 - error = response.substr(6);
1585 - var err = mainwp_js_get_error_not_detected_connect(error, 'html_msg', 'mainwp-message-zone');
1586 - if (false === err) {
1587 - feedback('mainwp-message-zone', error, 'red'); // it is not json error string.
1588 - }
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);
1589 1808 }
1590 - } else {
1591 - feedback('mainwp-message-zone', response, 'green');
1592 - }
1593 - setTimeout(function () {
1594 - window.location.reload()
1595 - }, 6000);
1596 - }
1597 1809
1598 - }(element));
1810 + }(element));
1599 1811 };
1600 1812
1601 1813 // Connect a new website
1602 -mainwp_managesites_add = function () {
1603 - managesites_init();
1604 - if (!jQuery('#mainwp_managesites_verify_installed_child').is(':checked')) {
1605 - jQuery('#mainwp_message_verify_installed_child').show();
1606 - scrollElementTop('mainwp_message_verify_installed_child');
1607 - return;
1608 - } else {
1609 - jQuery('#mainwp_message_verify_installed_child').hide();
1610 - }
1814 +let mainwp_managesites_add = function () {
1611 1815
1612 - var errors = [];
1816 + managesites_init();
1613 1817
1614 - if (jQuery('#mainwp_managesites_add_wpname').val().trim() == '') {
1615 - errors.push(__('Please enter a name for the website.'));
1616 - }
1617 - if (jQuery('#mainwp_managesites_add_wpurl').val().trim() == '') {
1618 - errors.push(__('Please enter a valid URL for your site.'));
1619 - } else {
1620 - var url = jQuery('#mainwp_managesites_add_wpurl').val().trim();
1621 - if (url.substr(-1) != '/') {
1622 - url += '/';
1623 - }
1818 + let valid_input = mainwp_managesites_add_valid();
1624 1819
1625 - jQuery('#mainwp_managesites_add_wpurl').val(url);
1626 -
1627 - if (!isUrl(jQuery('#mainwp_managesites_add_wpurl_protocol').val() + '://' + jQuery('#mainwp_managesites_add_wpurl').val())) {
1628 - errors.push(__('Please enter a valid URL for your site.'));
1820 + if (!valid_input) {
1821 + return;
1629 1822 }
1630 - }
1631 - if (jQuery('#mainwp_managesites_add_wpadmin').val().trim() == '') {
1632 - errors.push(__('Please enter a username of the website administrator.'));
1633 - }
1634 1823
1635 - if (errors.length > 0) {
1636 - feedback('mainwp-message-zone', errors.join('<br />'), 'yellow');
1637 - } else {
1638 - 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');
1639 1825
1640 1826 jQuery('#mainwp_managesites_add').attr('disabled', 'true'); //disable button to add..
1641 1827
1642 1828 //Check if valid user & rulewp is installed?
1643 - var url = jQuery('#mainwp_managesites_add_wpurl_protocol').val() + '://' + jQuery('#mainwp_managesites_add_wpurl').val().trim();
1644 - if (url.substr(-1) != '/') {
1645 - url += '/';
1829 + let url = jQuery('#mainwp_managesites_add_wpurl_protocol').val() + '://' + jQuery('#mainwp_managesites_add_wpurl').val().trim();
1830 +
1831 + if (!url.endsWith('/')) {
1832 + url += '/';
1646 1833 }
1647 1834
1648 - var name = jQuery('#mainwp_managesites_add_wpname').val().trim();
1649 - name = name.replace(/"/g, '&quot;');
1835 + let name = jQuery('#mainwp_managesites_add_wpname').val().trim();
1836 + name = name.replaceAll('"', '&quot;');
1650 1837
1651 - var data = mainwp_secure_data({
1652 - action: 'mainwp_checkwp',
1653 - name: name,
1654 - url: url,
1655 - admin: jQuery('#mainwp_managesites_add_wpadmin').val().trim(),
1656 - verify_certificate: jQuery('#mainwp_managesites_verify_certificate').is(':checked') ? 1 : 0,
1657 - ssl_version: jQuery('#mainwp_managesites_add_ssl_version').val(),
1658 - http_user: jQuery('#mainwp_managesites_add_http_user').val().trim(),
1659 - http_pass: jQuery('#mainwp_managesites_add_http_pass').val().trim()
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()
1660 1847 });
1661 1848
1662 - jQuery.post(ajaxurl, data, function (res_things) {
1663 - response = res_things.response;
1664 - response = response.trim();
1665 - var url = jQuery('#mainwp_managesites_add_wpurl_protocol').val() + '://' + jQuery('#mainwp_managesites_add_wpurl').val().trim();
1666 - if (url.substr(-1) != '/') {
1667 - url += '/';
1668 - }
1669 -
1670 - url = url.replace(/"/g, '&quot;');
1671 -
1672 - var show_resp = __('Click %1here%2 to see response from the child site.', '<a href="javascript:void(0)" class="mainwp-show-response">', '</a>');
1673 -
1674 - var resp_data = res_things.resp_data ? res_things.resp_data : '';
1675 - if ('0' == resp_data) {
1676 - resp_data = '';
1677 - }
1678 - jQuery('#mainwp-response-data-container').attr('resp-data', resp_data);
1679 -
1680 - if (response == 'HTTPERROR') {
1681 - 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>.'));
1682 - } else if (response == 'NOMAINWP') {
1683 - errors.push(mainwp_js_get_error_not_detected_connect());
1684 - } else if (response.substr(0, 5) == 'ERROR') {
1685 - if (response.length == 5) {
1686 - 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>.'));
1687 - } else {
1688 - errors.push(__('Error detected: ') + response.substr(6));
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 += '/';
1689 1856 }
1690 - } else if (response == 'OK') {
1691 - jQuery('#mainwp_managesites_add').attr('disabled', 'true'); //Disable add button
1692 1857
1693 - var name = jQuery('#mainwp_managesites_add_wpname').val();
1694 - name = name.replace(/"/g, '&quot;');
1695 - var group_ids = jQuery('#mainwp_managesites_add_addgroups').dropdown('get value');
1696 - var client_id = jQuery('#mainwp_managesites_add_client_id').dropdown('get value');
1697 - var data = mainwp_secure_data({
1698 - action: 'mainwp_addwp',
1699 - managesites_add_wpname: name,
1700 - managesites_add_wpurl: url,
1701 - managesites_add_wpadmin: jQuery('#mainwp_managesites_add_wpadmin').val(),
1702 - managesites_add_uniqueId: jQuery('#mainwp_managesites_add_uniqueId').val(),
1703 - ssl_verify: jQuery('#mainwp_managesites_verify_certificate').is(':checked') ? 1 : 0,
1704 - ssl_version: jQuery('#mainwp_managesites_add_ssl_version').val(),
1705 - groupids: group_ids,
1706 - clientid: client_id,
1707 - selected_icon: jQuery('#mainwp_managesites_add_site_select_icon_hidden').val(),
1708 - cust_color: jQuery('#mainwp_managesites_add_site_color').val(),
1709 - uploaded_icon: jQuery('#mainwp_managesites_add_site_uploaded_icon_hidden').val(),
1710 - managesites_add_http_user: jQuery('#mainwp_managesites_add_http_user').val(),
1711 - managesites_add_http_pass: jQuery('#mainwp_managesites_add_http_pass').val(),
1712 - });
1858 + url = url.replaceAll('"', '&quot;');
1713 1859
1714 - // to support add client reports tokens values
1715 - jQuery("input[name^='creport_token_']").each(function () {
1716 - var tname = jQuery(this).attr('name');
1717 - var tvalue = jQuery(this).val();
1718 - data[tname] = tvalue;
1719 - });
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>');
1720 1861
1721 - // support hooks fields
1722 - jQuery(".mainwp_addition_fields_addsite input").each(function () {
1723 - var tname = jQuery(this).attr('name');
1724 - var tvalue = jQuery(this).val();
1725 - data[tname] = tvalue;
1726 - });
1727 -
1728 - jQuery.post(ajaxurl, data, function (res_things) {
1729 - var site_id = 0;
1730 - if (res_things.error) {
1731 - response = 'Error detected: ' + res_things.error;
1732 - } else {
1733 - response = res_things.response;
1734 - site_id = res_things.siteid;
1735 - }
1736 - response = response.trim();
1737 - managesites_init();
1738 -
1739 - resp_data = res_things.resp_data ? res_things.resp_data : '';
1740 - if ('0' == resp_data) {
1862 + let resp_data = res_things.resp_data ? res_things.resp_data : '';
1863 + if ('0' == resp_data) {
1741 1864 resp_data = '';
1742 - }
1743 - jQuery('#mainwp-response-data-container').attr('resp-data', resp_data);
1865 + }
1866 + jQuery('#mainwp-response-data-container').attr('resp-data', resp_data);
1744 1867
1745 - if (response.substr(0, 5) == 'ERROR') {
1746 - jQuery('#mainwp-message-zone').removeClass('green');
1747 - feedback('mainwp-message-zone', response.substr(6) + (resp_data != '' ? '<br>' + show_resp : ''), 'red');
1748 - } else {
1749 - //Message the WP was added
1750 - jQuery('#mainwp-message-zone').removeClass('red');
1751 - feedback('mainwp-message-zone', response, 'green');
1752 -
1753 - if (site_id > 0) {
1754 - jQuery('.sync-ext-row').attr('status', 'queue');
1755 - setTimeout(function () {
1756 - mainwp_managesites_sync_extension_start_next(site_id);
1757 - }, 1000);
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));
1758 1877 }
1878 + } else if (response == 'OK') {
1879 + jQuery('#mainwp_managesites_add').attr('disabled', 'true'); //Disable add button
1759 1880
1760 - //Reset fields
1761 - jQuery('#mainwp_managesites_add_wpname').val('');
1762 - jQuery('#mainwp_managesites_add_wpurl').val('');
1763 - jQuery('#mainwp_managesites_add_wpurl_protocol').val('https');
1764 - jQuery('#mainwp_managesites_add_wpadmin').val('');
1765 - jQuery('#mainwp_managesites_add_uniqueId').val('');
1766 - jQuery('#mainwp_managesites_add_addgroups').dropdown('clear');
1767 - jQuery('#mainwp_managesites_verify_certificate').val(1);
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 + });
1768 1902
1903 + // to support add client reports tokens values
1769 1904 jQuery("input[name^='creport_token_']").each(function () {
1770 - jQuery(this).val('');
1905 + let tname = jQuery(this).attr('name');
1906 + let tvalue = jQuery(this).val();
1907 + data[tname] = tvalue;
1771 1908 });
1772 1909
1773 1910 // support hooks fields
1774 1911 jQuery(".mainwp_addition_fields_addsite input").each(function () {
1775 - jQuery(this).val('');
1912 + let tname = jQuery(this).attr('name');
1913 + let tvalue = jQuery(this).val();
1914 + data[tname] = tvalue;
1776 1915 });
1777 - }
1778 1916
1779 - jQuery('#mainwp_managesites_add').prop("disabled", false); //Enable add button
1780 - }, 'json');
1781 - }
1782 - if (errors.length > 0) {
1783 - jQuery('#mainwp-message-zone').removeClass('green');
1784 - managesites_init();
1785 - jQuery('#mainwp_managesites_add').prop("disabled", false); //Enable add button
1786 - if (resp_data != '') {
1787 - errors.push(show_resp);
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();
1927 +
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);
1933 +
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');
1940 +
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 + }
1947 +
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);
1957 +
1958 + jQuery("input[name^='creport_token_']").each(function () {
1959 + jQuery(this).val('');
1960 + });
1961 +
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');
1788 1970 }
1789 - feedback('mainwp-message-zone', errors.join('<br />'), 'red');
1790 - }
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 + }
1791 1980 }, 'json');
1792 - }
1793 1981 };
1794 1982
1795 -mainwp_managesites_sync_extension_start_next = function (siteId) {
1796 - while ((pluginToInstall = jQuery('.sync-ext-row[status="queue"]:first')) && (pluginToInstall.length > 0) && (bulkInstallCurrentThreads < 1 /* bulkInstallMaxThreads // to fix install plugins and apply settings failed issue */)) {
1797 - mainwp_managesites_sync_extension_start_specific(pluginToInstall, siteId);
1798 - }
1983 +let mainwp_managesites_add_valid = function () {
1799 1984
1800 - if ((pluginToInstall.length == 0) && (bulkInstallCurrentThreads == 0)) {
1801 - jQuery('#mwp_applying_ext_settings').remove();
1802 - }
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 + }
1992 +
1993 + let errors = [];
1994 +
1995 + if (jQuery('#mainwp_managesites_add_wpname').val().trim() == '') {
1996 + errors.push(MainWP.I18n.t('Please enter a name for the website.'));
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 + }
2005 +
2006 + jQuery('#mainwp_managesites_add_wpurl').val(url);
2007 +
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 + }
2011 + }
2012 + if (jQuery('#mainwp_managesites_add_wpadmin').val().trim() == '') {
2013 + errors.push(MainWP.I18n.t('Please enter a username of the website administrator.'));
2014 + }
2015 +
2016 + if (errors.length > 0) {
2017 + feedback('mainwp-message-zone', errors.join('<br />'), 'yellow');
2018 + return false;
2019 + }
2020 + return true;
2021 +}
2022 +
2023 +
2024 +let mainwp_managesites_sync_extension_start_next = function (siteId) {
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 + }
2031 +
2032 + if ((pluginToInstall.length == 0) && (bulkInstallCurrentThreads == 0)) { // NOSONAR - modified outside the function.
2033 + jQuery('#mwp_applying_ext_settings').remove();
2034 + }
1803 2035 };
1804 2036
1805 -mainwp_managesites_sync_extension_start_specific = function (pPluginToInstall, pSiteId) {
1806 - pPluginToInstall.attr('status', 'progress');
1807 - var syncGlobalSettings = pPluginToInstall.find(".sync-global-options input[type='checkbox']:checked").length > 0 ? true : false;
1808 - var install_plugin = pPluginToInstall.find(".sync-install-plugin input[type='checkbox']:checked").length > 0 ? true : false;
1809 - var apply_settings = pPluginToInstall.find(".sync-options input[type='checkbox']:checked").length > 0 ? true : false;
2037 +let mainwp_managesites_sync_extension_start_specific = function (pPluginToInstall, pSiteId) {
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;
1810 2041
1811 - if (syncGlobalSettings) {
1812 - mainwp_extension_apply_plugin_settings(pPluginToInstall, pSiteId, true);
1813 - } else if (install_plugin) {
1814 - mainwp_extension_prepareinstallplugin(pPluginToInstall, pSiteId);
1815 - } else if (apply_settings) {
1816 - mainwp_extension_apply_plugin_settings(pPluginToInstall, pSiteId, false);
1817 - } else {
1818 - mainwp_managesites_sync_extension_start_next(pSiteId);
1819 - return;
1820 - }
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 + }
1821 2052 };
1822 2053
1823 -mainwp_extension_prepareinstallplugin = function (pPluginToInstall, pSiteId) {
1824 - var site_Ids = [];
1825 - site_Ids.push(pSiteId);
1826 - bulkInstallCurrentThreads++;
1827 - var plugin_slug = pPluginToInstall.find(".sync-install-plugin").attr('slug');
1828 - var workingEl = pPluginToInstall.find(".sync-install-plugin i");
1829 - var statusEl = pPluginToInstall.find(".sync-install-plugin span.status");
2054 +let mainwp_extension_prepareinstallplugin = function (pPluginToInstall, pSiteId) {
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");
1830 2061
1831 - var data = {
1832 - action: 'mainwp_ext_prepareinstallplugintheme',
1833 - type: 'plugin',
1834 - slug: plugin_slug,
1835 - 'selected_sites[]': site_Ids,
1836 - selected_by: 'site',
1837 - };
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 + };
1838 2069
1839 - workingEl.show();
1840 - statusEl.html(__('Preparing for installation...'));
2070 + workingEl.show();
2071 + statusEl.html(MainWP.I18n.t('Preparing for installation...'));
1841 2072
1842 - jQuery.post(ajaxurl, data, function (response) {
1843 - workingEl.hide();
1844 - if (response.sites && response.sites[pSiteId]) {
1845 - statusEl.html(__('Installing...'));
1846 - var data = mainwp_secure_data({
1847 - action: 'mainwp_ext_performinstallplugintheme',
1848 - type: 'plugin',
1849 - url: response.url,
1850 - siteId: pSiteId,
1851 - activatePlugin: true,
1852 - overwrite: false,
1853 - });
1854 - workingEl.show();
1855 - jQuery.post(ajaxurl, data, function (response) {
2073 + jQuery.post(ajaxurl, data, function (response) {
1856 2074 workingEl.hide();
1857 - var apply_settings = false;
1858 - var syc_msg = '';
1859 - var _success = false;
1860 - if ((response.ok != undefined) && (response.ok[pSiteId] != undefined)) {
1861 - syc_msg = __('Installation successful!');
1862 - statusEl.html(syc_msg);
1863 - apply_settings = pPluginToInstall.find(".sync-options input[type='checkbox']:checked").length > 0 ? true : false;
1864 - if (apply_settings) {
1865 - mainwp_extension_apply_plugin_settings(pPluginToInstall, pSiteId, false);
1866 - }
1867 - _success = true;
1868 - } else if ((response.errors != undefined) && (response.errors[pSiteId] != undefined)) {
1869 - syc_msg = __('Installation failed!') + ': ' + response.errors[pSiteId][1];
1870 - statusEl.html(syc_msg);
1871 - 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--;
1872 2079 } else {
1873 - syc_msg = __('Installation failed!');
1874 - statusEl.html(syc_msg);
1875 - statusEl.css('color', 'red');
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 + }
2112 +
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 + }
2120 +
2121 + if (!apply_settings) {
2122 + bulkInstallCurrentThreads--;
2123 + mainwp_managesites_sync_extension_start_next(pSiteId);
2124 + }
2125 + }, 'json');
1876 2126 }
2127 + }, 'json');
2128 +}
1877 2129
2130 +let mainwp_extension_apply_plugin_settings = function (pPluginToInstall, pSiteId, pGlobal) {
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++;
2136 +
2137 + let data = mainwp_secure_data({
2138 + action: 'mainwp_ext_applypluginsettings',
2139 + ext_dir_slug: extSlug,
2140 + siteId: pSiteId
2141 + });
2142 +
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');
2171 + }
2172 +
1878 2173 if (syc_msg != '') {
1879 - if (_success)
1880 - syc_msg = '<span style="color:#0073aa">' + syc_msg + '!</span>';
1881 - else
1882 - syc_msg = '<span style="color:red">' + syc_msg + '!</span>';
1883 - jQuery('#mainwp-message-zone').append('<br/>' + pPluginToInstall.find(".sync-install-plugin").attr('plugin_name') + ' ' + 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);
1884 2184 }
2185 + bulkInstallCurrentThreads--;
2186 + mainwp_managesites_sync_extension_start_next(pSiteId);
2187 + }, 'json');
2188 +}
1885 2189
1886 - if (!apply_settings) {
1887 - bulkInstallCurrentThreads--;
1888 - mainwp_managesites_sync_extension_start_next(pSiteId);
2190 +// Test Connection (Add Site Page)
2191 +let mainwp_managesites_test = function () {
2192 +
2193 + let errors = [];
2194 +
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 += '/';
1889 2203 }
1890 - }, 'json');
1891 - } else {
1892 - statusEl.css('color', 'red');
1893 - statusEl.html(__('Error while preparing the installation. Please, try again.'));
1894 - bulkInstallCurrentThreads--;
2204 +
2205 + if (!isUrl(url)) {
2206 + errors.push(MainWP.I18n.t('Please enter a valid URL for your site'));
2207 + }
1895 2208 }
1896 - }, 'json');
1897 -}
1898 2209
1899 -mainwp_extension_apply_plugin_settings = function (pPluginToInstall, pSiteId, pGlobal) {
1900 - var extSlug = pPluginToInstall.attr('slug');
1901 - var workingEl = pPluginToInstall.find(".options-row i");
1902 - var statusEl = pPluginToInstall.find(".options-row span.status");
1903 - if (pGlobal)
1904 - bulkInstallCurrentThreads++;
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();
1905 2216
1906 - var data = mainwp_secure_data({
1907 - action: 'mainwp_ext_applypluginsettings',
1908 - ext_dir_slug: extSlug,
1909 - siteId: pSiteId
1910 - });
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;
1911 2220
1912 - workingEl.show();
1913 - statusEl.html(__('Applying settings...'));
1914 - jQuery.post(ajaxurl, data, function (response) {
1915 - workingEl.hide();
1916 - var syc_msg = '';
1917 - var _success = false;
1918 - if (response) {
1919 - if (response.result && response.result == 'success') {
1920 - var msg = '';
1921 - if (response.message != undefined) {
1922 - msg = ' ' + response.message;
2221 + if (!url.endsWith('/')) {
2222 + url += '/';
1923 2223 }
1924 - statusEl.html(__('Applying settings successful!') + msg);
1925 - syc_msg = __('Successful');
1926 - _success = true
1927 - } else if (response.error != undefined) {
1928 - statusEl.html(__('Applying settings failed!') + ': ' + response.error);
1929 - statusEl.css('color', 'red');
1930 - syc_msg = __('failed');
1931 - } else {
1932 - statusEl.html(__('Applying settings failed!'));
1933 - statusEl.css('color', 'red');
1934 - syc_msg = __('failed');
1935 - }
1936 - } else {
1937 - statusEl.html(__('Undefined error!'));
1938 - statusEl.css('color', 'red');
1939 - syc_msg = __('failed');
1940 - }
1941 2224
1942 - if (syc_msg != '') {
1943 - if (_success)
1944 - syc_msg = '<span style="color:#0073aa">' + syc_msg + '!</span>';
1945 - else
1946 - syc_msg = '<span style="color:red">' + syc_msg + '!</span>';
1947 - if (pGlobal) {
1948 - syc_msg = __('Apply global %1 options', pPluginToInstall.attr('ext_name')) + ' ' + syc_msg;
1949 - } else {
1950 - syc_msg = __('Apply %1 settings', pPluginToInstall.find('.sync-install-plugin').attr('plugin_name')) + ' ' + syc_msg;
1951 - }
1952 - jQuery('#mainwp-message-zone').append('<br/>' + syc_msg);
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 + });
2233 +
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');
1953 2270 }
1954 - bulkInstallCurrentThreads--;
1955 - mainwp_managesites_sync_extension_start_next(pSiteId);
1956 - }, 'json');
1957 -}
2271 +};
1958 2272
1959 -// Test Connection (Add Site Page)
1960 -mainwp_managesites_test = function () {
2273 +// Test Connection (Edit Site Page)
2274 +let mainwp_managesites_edit_test = function () {
1961 2275
1962 - var errors = [];
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 + '.' : '';
1963 2280
1964 - if (jQuery('#mainwp_managesites_add_wpurl').val().trim() == '') {
1965 - errors.push(__('Please enter a valid URL for your site.'));
1966 - } else {
1967 - var clean_url = jQuery('#mainwp_managesites_add_wpurl').val().trim();
1968 - var protocol = jQuery('#mainwp_managesites_add_wpurl_protocol').val();
1969 - url = protocol + '://' + clean_url;
1970 - if (url.substr(-1) != '/') {
1971 - url += '/';
1972 - }
2281 + let url = protocol + '://' + with_www + clean_url;
1973 2282
1974 - if (!isUrl(url)) {
1975 - errors.push(__('Please enter a valid URL for your site'));
2283 + if (!url.endsWith('/')) {
2284 + url += '/';
1976 2285 }
1977 - }
1978 2286
1979 - if (errors.length > 0) {
1980 - feedback('mainwp-message-zone', errors.join('<br />'), 'red');
1981 - } else {
1982 2287 jQuery('#mainwp-test-connection-modal').modal('setting', 'closable', false).modal('show');
1983 2288 jQuery('#mainwp-test-connection-modal .dimmer').show();
1984 2289 jQuery('#mainwp-test-connection-modal .content #mainwp-test-connection-result').hide();
1985 2290
1986 - var clean_url = jQuery('#mainwp_managesites_add_wpurl').val().trim();
1987 - var protocol = jQuery('#mainwp_managesites_add_wpurl_protocol').val();
1988 - url = protocol + '://' + clean_url;
1989 -
1990 - if (url.substr(-1) != '/') {
1991 - url += '/';
1992 - }
1993 -
1994 - var data = mainwp_secure_data({
1995 - action: 'mainwp_testwp',
1996 - url: url,
1997 - test_verify_cert: jQuery('#mainwp_managesites_verify_certificate').is(':checked') ? 1 : 0,
1998 - ssl_version: jQuery('#mainwp_managesites_add_ssl_version').val(),
1999 - http_user: jQuery('#mainwp_managesites_add_http_user').val(),
2000 - http_pass: jQuery('#mainwp_managesites_add_http_pass').val()
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()
2001 2298 });
2002 2299
2003 - jQuery.post(ajaxurl, data, function (response) {
2004 - jQuery('#mainwp-test-connection-modal .dimmer').hide();
2005 - jQuery('#mainwp-test-connection-modal .content #mainwp-test-connection-result i').removeClass('red green check times');
2006 - jQuery('#mainwp-test-connection-modal .content #mainwp-test-connection-result .content span').html('');
2007 - jQuery('#mainwp-test-connection-modal .content #mainwp-test-connection-result .content .sub.header').html('');
2008 - if (response.error) {
2009 - if (response.httpCode) {
2010 - jQuery('#mainwp-test-connection-modal .content #mainwp-test-connection-result').show();
2011 - jQuery('#mainwp-test-connection-modal .content #mainwp-test-connection-result i').addClass('red times');
2012 - jQuery('#mainwp-test-connection-modal .content #mainwp-test-connection-result .content span').html(__('Connection failed!'));
2013 - 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);
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 + }
2014 2329 } else {
2015 - jQuery('#mainwp-test-connection-modal .content #mainwp-test-connection-result').show();
2016 - jQuery('#mainwp-test-connection-modal .content #mainwp-test-connection-result i').addClass('red times');
2017 - jQuery('#mainwp-test-connection-modal .content #mainwp-test-connection-result .content span').html(__('Connection test failed.'));
2018 - jQuery('#mainwp-test-connection-modal .content #mainwp-test-connection-result .content .sub.header').html(__('Error message:') + ' ' + response.error);
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.'));
2019 2334 }
2020 - } else if (response.httpCode) {
2021 - if (response.httpCode == '200') {
2022 - jQuery('#mainwp-test-connection-modal .content #mainwp-test-connection-result').show();
2023 - jQuery('#mainwp-test-connection-modal .content #mainwp-test-connection-result i').addClass('green check');
2024 - jQuery('#mainwp-test-connection-modal .content #mainwp-test-connection-result .content span').html(__('Connection successful!'));
2025 - 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 + ')' : ''));
2026 - } else {
2027 - jQuery('#mainwp-test-connection-modal .content #mainwp-test-connection-result').show();
2028 - jQuery('#mainwp-test-connection-modal .content #mainwp-test-connection-result i').addClass('red times');
2029 - jQuery('#mainwp-test-connection-modal .content #mainwp-test-connection-result .content span').html(__('Connection test failed.'));
2030 - 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 + ')' : ''));
2031 - }
2032 - } else {
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('red times');
2035 - jQuery('#mainwp-test-connection-modal .content #mainwp-test-connection-result .content span').html(__('Connection test failed.'));
2036 - jQuery('#mainwp-test-connection-modal .content #mainwp-test-connection-result .content .sub.header').html(__('Invalid response from the server, please try again.'));
2037 - }
2038 2335 }, 'json');
2039 - }
2040 2336 };
2041 2337
2042 -// Test Connection (Edit Site Page)
2043 -mainwp_managesites_edit_test = function () {
2338 +let managesites_remove = function (obj) {
2339 + managesites_init();
2044 2340
2045 - var clean_url = jQuery('#mainwp_managesites_edit_siteurl').val();
2046 - var protocol = jQuery('#mainwp_managesites_edit_siteurl_protocol').val();
2341 + let name = jQuery(obj).attr('site-name');
2342 + let id = jQuery(obj).attr('site-id');
2047 2343
2048 - url = protocol + '://' + clean_url;
2344 + let msg = MainWP.I18n.t('Are you sure you want to remove') + ' ' + name + ' ' + MainWP.I18n.t('from your MainWP Dashboard?');
2049 2345
2050 - if (url.substr(-1) != '/') {
2051 - url += '/';
2052 - }
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 + });
2053 2352
2054 - jQuery('#mainwp-test-connection-modal').modal('setting', 'closable', false).modal('show');
2055 - jQuery('#mainwp-test-connection-modal .dimmer').show();
2056 - jQuery('#mainwp-test-connection-modal .content #mainwp-test-connection-result').hide();
2353 + jQuery.post(ajaxurl, data, function (response) {
2057 2354
2058 - var data = mainwp_secure_data({
2059 - action: 'mainwp_testwp',
2060 - url: url,
2061 - test_verify_cert: jQuery('#mainwp_managesites_edit_verifycertificate').val(),
2062 - ssl_version: jQuery('#mainwp_managesites_edit_ssl_version').val(),
2063 - http_user: jQuery('#mainwp_managesites_edit_http_user').val(),
2064 - http_pass: jQuery('#mainwp_managesites_edit_http_pass').val()
2065 - });
2355 + managesites_init();
2066 2356
2067 - jQuery.post(ajaxurl, data, function (response) {
2068 - jQuery('#mainwp-test-connection-modal .dimmer').hide();
2069 - jQuery('#mainwp-test-connection-modal .content #mainwp-test-connection-result i').removeClass('red green check times');
2070 - jQuery('#mainwp-test-connection-modal .content #mainwp-test-connection-result .content span').html('');
2071 - jQuery('#mainwp-test-connection-modal .content #mainwp-test-connection-result .content .sub.header').html('');
2072 - if (response.error) {
2073 - if (response.httpCode) {
2074 - jQuery('#mainwp-test-connection-modal .content #mainwp-test-connection-result').show();
2075 - jQuery('#mainwp-test-connection-modal .content #mainwp-test-connection-result i').addClass('red times');
2076 - jQuery('#mainwp-test-connection-modal .content #mainwp-test-connection-result .content span').html(__('Connection failed!'));
2077 - 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);
2078 - } else {
2079 - jQuery('#mainwp-test-connection-modal .content #mainwp-test-connection-result').show();
2080 - jQuery('#mainwp-test-connection-modal .content #mainwp-test-connection-result i').addClass('red times');
2081 - jQuery('#mainwp-test-connection-modal .content #mainwp-test-connection-result .content span').html(__('Connection test failed.'));
2082 - jQuery('#mainwp-test-connection-modal .content #mainwp-test-connection-result .content .sub.header').html(__('Error message:') + ' ' + response.error);
2083 - }
2084 - } else if (response.httpCode) {
2085 - if (response.httpCode == '200') {
2086 - jQuery('#mainwp-test-connection-modal .content #mainwp-test-connection-result').show();
2087 - jQuery('#mainwp-test-connection-modal .content #mainwp-test-connection-result i').addClass('green check');
2088 - jQuery('#mainwp-test-connection-modal .content #mainwp-test-connection-result .content span').html(__('Connection successful!'));
2089 - 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 + ')' : ''));
2090 - } else {
2091 - jQuery('#mainwp-test-connection-modal .content #mainwp-test-connection-result').show();
2092 - jQuery('#mainwp-test-connection-modal .content #mainwp-test-connection-result i').addClass('red times');
2093 - jQuery('#mainwp-test-connection-modal .content #mainwp-test-connection-result .content span').html(__('Connection test failed.'));
2094 - 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 + ')' : ''));
2095 - }
2096 - } else {
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('red times');
2099 - jQuery('#mainwp-test-connection-modal .content #mainwp-test-connection-result .content span').html(__('Connection test failed.'));
2100 - jQuery('#mainwp-test-connection-modal .content #mainwp-test-connection-result .content .sub.header').html(__('Invalid response from the server, please try again.'));
2101 - }
2102 - }, 'json');
2103 -};
2357 + let result = '';
2358 + let error = '';
2104 2359
2105 -managesites_remove = function (obj) {
2106 - managesites_init();
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 + }
2107 2369
2108 - var name = jQuery(obj).attr('site-name');
2109 - var id = jQuery(obj).attr('site-id');
2370 + if (error != '') {
2371 + feedback('mainwp-message-zone', error, 'red');
2372 + }
2110 2373
2111 - var msg = sprintf(__('Are you sure you want to remove %1 from your MainWP Dashboard?', name));
2374 + if (result != '') {
2375 + feedback('mainwp-message-zone', result, 'green');
2376 + }
2112 2377
2113 - mainwp_confirm(msg, function () {
2114 - 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>');
2115 - var data = mainwp_secure_data({
2116 - action: 'mainwp_removesite',
2117 - id: id
2118 - });
2378 + jQuery('tr#child-site-' + id).remove();
2119 2379
2120 - jQuery.post(ajaxurl, data, function (response) {
2380 + }, 'json');
2381 + }, false, false, false, 'REMOVE');
2382 + return false;
2383 +};
2121 2384
2122 - managesites_init();
2385 +jQuery(function () {
2123 2386
2124 - var result = '';
2125 - var error = '';
2387 + jQuery(document).on('click', '#mainwp_managesites_add', function () {
2388 + mainwp_managesites_add();
2389 + });
2126 2390
2127 - if (response.error != undefined) {
2128 - error = response.error;
2129 - } else if (response.result == 'SUCCESS') {
2130 - result = '<i class="close icon"></i>' + __('The site has been removed and the MainWP Child plugin has been disabled.');
2131 - } else if (response.result == 'NOSITE') {
2132 - error = '<i class="close icon"></i>' + __('The requested site has not been found.');
2133 - } else {
2134 - result = '<i class="close icon"></i>' + __('The site has been removed. Please make sure that the MainWP Child plugin has been deactivated properly.');
2135 - }
2391 + // Hanlde click submit form import website
2392 + jQuery(document).on('click', '#mainwp_managesites_bulkadd', function () {
2136 2393
2137 - if (error != '') {
2138 - feedback('mainwp-message-zone', error, 'red');
2139 - }
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 + });
2140 2403
2141 - if (result != '') {
2142 - feedback('mainwp-message-zone', result, 'green');
2143 - }
2404 + // Trigger Connection Test (Add Site Page)
2405 + jQuery(document).on('click', '#mainwp_managesites_test', function () {
2406 + mainwp_managesites_test();
2407 + });
2144 2408
2145 - jQuery('tr#child-site-' + id).remove();
2409 + // Trigger Connection Test (Edit Site Page)
2410 + jQuery(document).on('click', '#mainwp_managesites_edit_test', function () {
2411 + mainwp_managesites_edit_test();
2412 + });
2146 2413
2147 - }, 'json');
2148 - }, false, false, false, 'REMOVE');
2149 - return false;
2150 -};
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 + });
2151 2426
2152 -jQuery(document).ready(function () {
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 + });
2153 2440
2154 - jQuery(document).on('click', '#mainwp_managesites_add', function (event) {
2155 - mainwp_managesites_add(event);
2156 - });
2157 -
2158 - jQuery(document).on('click', '#mainwp_managesites_bulkadd', function () {
2159 - if (jQuery('#mainwp_managesites_file_bulkupload').val() == '') {
2160 - setHtml('#mainwp-message-zone', __('Please enter csv file for upload.'), false);
2161 - } else {
2162 - jQuery('#mainwp_managesites_bulkadd_form').submit();
2163 - }
2164 - return false;
2165 - });
2166 -
2167 - // Trigger Connection Test (Add Site Page)
2168 - jQuery(document).on('click', '#mainwp_managesites_test', function (event) {
2169 - mainwp_managesites_test(event);
2170 - });
2171 -
2172 - // Trigger Connection Test (Edit Site Page)
2173 - jQuery(document).on('click', '#mainwp_managesites_edit_test', function (event) {
2174 - mainwp_managesites_edit_test(event);
2175 - });
2176 -
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 + });
2177 2445 });
2178 2446
2179 2447 /**
2180 2448 * Add new user
2181 2449 */
2182 -jQuery(document).ready(function () {
2183 - jQuery(document).on('click', '#bulk_add_createuser', function (event) {
2184 - mainwp_createuser(event);
2185 - });
2186 - jQuery('#bulk_import_createuser').on('click', function () {
2187 - mainwp_bulkupload_users();
2188 - });
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');
2189 2460 });
2190 2461
2191 -mainwp_createuser = function () {
2192 - var cont = true;
2193 - if (jQuery('#user_login').val() == '') {
2194 - feedback('mainwp-message-zone', __('Username field is required! Please enter a username.'), 'yellow');
2195 - cont = false;
2196 - }
2462 +jQuery(function () {
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 + });
2469 +});
2197 2470
2198 - if (jQuery('#email').val() == '') {
2199 - feedback('mainwp-message-zone', __('E-mail field is required! Please enter an email address.'), 'yellow');
2200 - cont = false;
2201 - }
2471 +let mainwp_createuser = function () {
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 + }
2202 2477
2203 - if (jQuery('#password').val() == '') {
2204 - feedback('mainwp-message-zone', __('Password field is required! Please enter the wanted password or generate a random one.'), 'yellow');
2205 - cont = false;
2206 - }
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 + }
2207 2482
2208 - if (jQuery('#select_by').val() == 'site') {
2209 - var selected_sites = [];
2210 - jQuery("input[name='selected_sites[]']:checked").each(function () {
2211 - selected_sites.push(jQuery(this).val());
2212 - });
2213 - if (selected_sites.length == 0) {
2214 - feedback('mainwp-message-zone', __('Please select at least one website or group or client.'), 'yellow');
2215 - cont = false;
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;
2216 2486 }
2217 - } else if (jQuery('#select_by').val() == 'client') {
2218 - var selected_clients = [];
2219 - jQuery("input[name='selected_clients[]']:checked").each(function () {
2220 - selected_clients.push(jQuery(this).val());
2221 - });
2222 - if (selected_clients.length == 0) {
2223 - feedback('mainwp-message-zone', __('Please select at least one website or group or client.'), 'yellow');
2224 - cont = false;
2225 - }
2226 - } else {
2227 - var selected_groups = [];
2228 - jQuery("input[name='selected_groups[]']:checked").each(function () {
2229 - selected_groups.push(jQuery(this).val());
2230 - });
2231 - if (selected_groups.length == 0) {
2232 - feedback('mainwp-message-zone', __('Please select at least one website or group or client.'), 'yellow');
2233 - cont = false;
2234 - }
2235 - }
2236 2487
2237 - if (cont) {
2238 - jQuery('#mainwp-message-zone').removeClass('red green yellow');
2239 - jQuery('#mainwp-message-zone').html('<i class="notched circle loading icon"></i> ' + __('Creating the user. Please wait...'));
2240 - jQuery('#mainwp-message-zone').show();
2241 - jQuery('#bulk_add_createuser').attr('disabled', 'disabled');
2242 - //Add user via ajax!!
2243 - var data = mainwp_secure_data({
2244 - action: 'mainwp_bulkadduser',
2245 - 'select_by': jQuery('#select_by').val(),
2246 - 'selected_groups[]': selected_groups,
2247 - 'selected_sites[]': selected_sites,
2248 - 'selected_clients[]': selected_clients,
2249 - 'user_login': jQuery('#user_login').val(),
2250 - 'email': jQuery('#email').val(),
2251 - 'url': jQuery('#url').val(),
2252 - 'first_name': jQuery('#first_name').val(),
2253 - 'last_name': jQuery('#last_name').val(),
2254 - 'pass1': jQuery('#password').val(),
2255 - 'pass2': jQuery('#password').val(),
2256 - 'send_password': jQuery('#send_password').attr('checked'),
2257 - 'role': jQuery('#role').val()
2258 - });
2488 + let selected_sites = [];
2489 + let selected_clients = [];
2490 + let selected_groups = [];
2259 2491
2260 - jQuery.post(ajaxurl, data, function (response) {
2261 - response = response.trim();
2262 - jQuery('#mainwp-message-zone').hide();
2263 - jQuery('#bulk_add_createuser').prop("disabled", false);
2264 - if (response.substring(0, 5) == 'ERROR') {
2265 - var responseObj = JSON.parse(response.substring(6));
2266 - if (responseObj.error == undefined) {
2267 - var errorMessageList = responseObj[1];
2268 - var errorMessage = '';
2269 - for (var i = 0; i < errorMessageList.length; i++) {
2270 - if (errorMessage != '')
2271 - errorMessage = errorMessage + "<br />";
2272 - errorMessage = errorMessage + errorMessageList[i];
2273 - }
2274 - if (errorMessage != '') {
2275 - feedback('mainwp-message-zone', errorMessage, 'red');
2276 - }
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;
2277 2499 }
2278 - } else {
2279 - jQuery('#mainwp-add-new-user-form').append(response);
2280 - jQuery('#mainwp-creating-new-user-modal').modal('setting', 'closable', false).modal('show');
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 + }
2516 + }
2281 2517
2282 - }
2283 - });
2284 - }
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 + });
2539 +
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');
2564 + }
2565 + });
2566 + }
2285 2567 };
2286 2568
2287 2569 /**
2288 2570 * InstallPlugins/Themes
2289 2571 */
2290 -jQuery(document).ready(function () {
2291 - jQuery('#MainWPInstallBulkNavSearch').on('click', function (event) {
2292 - event.preventDefault();
2293 - jQuery('#mainwp_plugin_bulk_install_btn').attr('bulk-action', 'install');
2294 - jQuery('.mainwp-browse-plugins').show();
2295 - jQuery('.mainwp-upload-plugin').hide();
2296 - jQuery('#mainwp-search-plugins-form').show();
2297 - });
2298 - jQuery('#MainWPInstallBulkNavUpload').on('click', function (event) {
2299 - event.preventDefault();
2300 - jQuery('#mainwp_plugin_bulk_install_btn').attr('bulk-action', 'upload');
2301 - jQuery('.mainwp-upload-plugin').show();
2302 - jQuery('.mainwp-browse-plugins').hide();
2303 - jQuery('#mainwp-search-plugins-form').hide();
2304 - });
2572 +jQuery(function () {
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 + });
2305 2590
2306 - // not used?
2307 - jQuery(document).on('click', '.filter-links li.plugin-install a', function (event) {
2308 - event.preventDefault();
2309 - jQuery('.filter-links li.plugin-install a').removeClass('current');
2310 - jQuery(this).addClass('current');
2311 - var tab = jQuery(this).parent().attr('tab');
2312 - if (tab == 'search') {
2313 - mainwp_install_search(event);
2314 - } else {
2315 - jQuery('#mainwp_installbulk_s').val('');
2316 - jQuery('#mainwp_installbulk_tab').val(tab);
2317 - mainwp_install_plugin_tab_search('tab:' + tab);
2318 - }
2319 - });
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 + });
2320 2605
2321 - jQuery(document).on('click', '#mainwp_plugin_bulk_install_btn', function () {
2322 - var act = jQuery(this).attr('bulk-action');
2323 - if (act == 'install') {
2324 - var selected = jQuery("input[type='radio'][name='install-plugin']:checked");
2325 - if (selected.length == 0) {
2326 - feedback('mainwp-message-zone', __('Please select plugin to install files.'), 'yellow');
2327 - } else {
2328 - var selectedId = /^install-([^-]*)-(.*)$/.exec(selected.attr('id'));
2329 - if (selectedId) {
2330 - mainwp_install_bulk('plugin', selectedId[2], selected.attr('plugin-name'), selected.attr('plugin-version'));
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');
2331 2620 }
2332 - }
2333 - } else if (act == 'upload') {
2334 - mainwp_upload_bulk('plugins');
2335 - }
2336 2621
2337 - return false;
2338 - });
2622 + return false;
2623 + });
2339 2624
2340 - jQuery(document).on('click', '#mainwp_theme_bulk_install_btn', function () {
2341 - var act = jQuery(this).attr('bulk-action');
2342 - if (act == 'install') {
2343 - var selected = jQuery("input[type='radio'][name='install-theme']:checked");
2344 - if (selected.length == 0) {
2345 - feedback('mainwp-message-zone', __('Please select theme to install files.'), 'yellow');
2346 - } else {
2347 - var selectedId = /^install-([^-]*)-(.*)$/.exec(selected.attr('id'));
2348 - if (selectedId)
2349 - mainwp_install_bulk('theme', selectedId[2], selected.attr('theme-name'), selected.attr('theme-version'));
2350 - }
2351 - } else if (act == 'upload') {
2352 - mainwp_upload_bulk('themes');
2353 - }
2354 - return false;
2355 - });
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 + });
2356 2641 });
2357 2642
2358 2643 // Generate the Go to WP Admin link
2359 -mainwp_links_visit_site_and_admin = function (url, siteId) {
2360 - var links = '';
2361 - if (url != '') {
2362 - links += '<a href="' + url + '" target="_blank" class="mainwp-may-hide-referrer"><i class="external alternate icon"></i></a> ';
2363 - }
2364 - links += '<a href="admin.php?page=SiteOpen&newWindow=yes&websiteid=' + siteId + '&_opennonce=' + mainwpParams._wpnonce + '" target="_blank"><i class="sign in alternate icon"></i></a>';
2365 - 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;
2366 2651 }
2367 2652
2368 -bulkInstallTotal = 0;
2653 +mainwpVars.bulkInstallTotal = 0;
2369 2654 bulkInstallDone = 0;
2370 2655
2371 2656 /**
2372 2657 * Install Plugin/Theme from WP.org.
@@ -2377,100 +2662,98 @@
2377 2662 * @param string slug Plugin or theme slug.
2378 2663 *
2379 2664 * @return void
2380 2665 */
2381 -mainwp_install_bulk = function (type, slug, name) {
2382 - var data = mainwp_secure_data({
2383 - action: 'mainwp_preparebulkinstallplugintheme',
2384 - type: type,
2385 - slug: slug,
2386 - name: name,
2387 - selected_by: jQuery('#select_by').val()
2388 - });
2389 - var 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>';
2666 +let mainwp_install_bulk = function (type, slug, name) {
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>';
2390 2675
2391 - if (jQuery('#select_by').val() == 'site') {
2676 + if (jQuery('input[name="select_by"]').val() == 'site') {
2392 2677
2393 - var selected_sites = [];
2678 + let selected_sites = [];
2394 2679
2395 - jQuery("input[name='selected_sites[]']:checked").each(function () {
2396 - selected_sites.push(jQuery(this).val());
2397 - });
2680 + jQuery("input[name='selected_sites[]']:checked").each(function () {
2681 + selected_sites.push(jQuery(this).val());
2682 + });
2398 2683
2399 - if (selected_sites.length == 0) {
2400 - feedback('mainwp-message-zone', __('Please select at least one website or a group or client.', 'mainwp'), 'yellow');
2401 - return;
2402 - }
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 + }
2403 2688
2404 - data['selected_sites[]'] = selected_sites;
2689 + data['selected_sites[]'] = selected_sites;
2405 2690
2406 - } else if (jQuery('#select_by').val() == 'client') {
2691 + } else if (jQuery('input[name="select_by"]').val() == 'client') {
2407 2692
2408 - var selected_clients = [];
2693 + let selected_clients = [];
2409 2694
2410 - jQuery("input[name='selected_clients[]']:checked").each(function () {
2411 - selected_clients.push(jQuery(this).val());
2412 - });
2695 + jQuery("input[name='selected_clients[]']:checked").each(function () {
2696 + selected_clients.push(jQuery(this).val());
2697 + });
2413 2698
2414 - if (selected_clients.length == 0) {
2415 - feedback('mainwp-message-zone', __('Please select at least one website or a group or client.', 'mainwp'), 'yellow');
2416 - return;
2417 - }
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 + }
2418 2703
2419 - data['selected_clients[]'] = selected_clients;
2704 + data['selected_clients[]'] = selected_clients;
2420 2705
2421 - } else {
2422 - var selected_groups = [];
2706 + } else {
2707 + let selected_groups = [];
2423 2708
2424 - jQuery("input[name='selected_groups[]']:checked").each(function () {
2425 - selected_groups.push(jQuery(this).val());
2426 - });
2709 + jQuery("input[name='selected_groups[]']:checked").each(function () {
2710 + selected_groups.push(jQuery(this).val());
2711 + });
2427 2712
2428 - if (selected_groups.length == 0) {
2429 - feedback('mainwp-message-zone', __('Please select at least one website or a group or client.', 'mainwp'), 'yellow');
2430 - return;
2431 - }
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 + }
2432 2717
2433 - data['selected_groups[]'] = selected_groups;
2718 + data['selected_groups[]'] = selected_groups;
2434 2719
2435 - }
2720 + }
2436 2721
2437 - jQuery('#plugintheme-installation-queue').html(placeholder);
2438 - jQuery.post(ajaxurl, data, function (type, activatePlugin, overwrite) {
2439 - return function (response) {
2440 - var installQueueContent = '';
2441 - bulkInstallDone = 0;
2442 - installQueueContent += '<div id="bulk_install_info"></div>';
2443 - 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">';
2444 2729
2445 - for (var siteId in response.sites) {
2446 - var site = response.sites[siteId];
2447 - installQueueContent +=
2448 - '<div class="siteBulkInstall item" siteid="' + siteId + '" status="queue">' +
2449 - '<div class="right floated content">' +
2450 - '<span class="queue" data-inverted="" data-position="left center" data-tooltip="' + __('Queued') + '"><i class="clock outline icon"></i></span>' +
2451 - '<span class="progress" data-inverted="" data-position="left center" data-tooltip="' + __('Installing...') + '" style="display:none"><i class="notched circle loading icon"></i></span>' +
2452 - '<span class="status"></span>' +
2453 - '</div>' +
2454 - '<div class="content">' + mainwp_links_visit_site_and_admin('', siteId) + ' ' + '<a href="' + site['url'] + '">' + site['name'].replace(/\\(.)/mg, "$1") + '</a></div>' +
2455 - '</div>';
2456 - bulkInstallTotal++;
2457 - }
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 + }
2458 2743
2459 - installQueueContent += '</div>';
2744 + installQueueContent += '</div>';
2460 2745
2461 - jQuery('#plugintheme-installation-queue').html(installQueueContent);
2462 - jQuery('#plugintheme-installation-progress-modal .mainwp-modal-progress').progress({ value: 0, total: bulkInstallTotal });
2463 - mainwp_install_bulk_start_next(type, response.url, activatePlugin, overwrite, slug, response);
2464 - }
2465 - }(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');
2466 2751
2467 - jQuery('#plugintheme-installation-progress-modal').modal('setting', 'closable', false).modal('show');
2752 + jQuery('#plugintheme-installation-progress-modal').modal('setting', 'closable', false).modal('show');
2468 2753
2469 2754 };
2470 2755
2471 -bulkInstallMaxThreads = mainwpParams['maximumInstallUpdateRequests'] == undefined ? 3 : mainwpParams['maximumInstallUpdateRequests'];
2472 -bulkInstallCurrentThreads = 0;
2473 2756
2474 2757 /**
2475 2758 * Install Plugin/Theme from WP.org.
2476 2759 *
@@ -2482,32 +2765,32 @@
2482 2765 * @param bool overwrite Determines if the item should overwrite exisitng version.
2483 2766 *
2484 2767 * @return void
2485 2768 */
2486 -mainwp_install_bulk_start_next = function (type, url, activatePlugin, overwrite, slug, installResults) {
2487 - while ((siteToInstall = jQuery('.siteBulkInstall[status="queue"]:first')) && (siteToInstall.length > 0) && (bulkInstallCurrentThreads < bulkInstallMaxThreads)) {
2488 - mainwp_install_bulk_start_specific(type, url, activatePlugin, overwrite, siteToInstall, slug, installResults);
2489 - }
2490 - if (bulkInstallDone == bulkInstallTotal && bulkInstallTotal != 0) {
2491 - jQuery('#bulk_install_info').before('<div class="ui info message">' + mainwp_install_bulk_you_know_msg(type, 1) + '</div>');
2492 - if (jQuery('.mainwp-cost-tracker-assistant-add-to-cost-tracker-button').length > 0) { // to support add to cost tracker pro.
2493 - if (installResults.add_to_cost_tracker_id != undefined) {
2494 - if (installResults.add_to_cost_tracker_id > 0) {
2495 - jQuery('.mainwp-cost-tracker-assistant-add-to-cost-tracker-button').text(_('Edit Cost Tracker'));
2496 - jQuery('#mainwp-cost-tracker-assistant-add-to-tracker-modal .header').text(_('Edit Cost Tracker'));
2769 +let mainwp_install_bulk_start_next = function (type, url, activatePlugin, overwrite, slug, installResults) { // NOSONAR - complex.
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 + }
2497 2791 }
2498 - jQuery('.mainwp-cost-tracker-assistant-add-to-cost-tracker-button').attr('disabled', false);
2499 - jQuery('.mainwp-cost-tracker-assistant-add-to-cost-tracker-button').removeClass('disabled');
2500 - jQuery('.mainwp-cost-tracker-assistant-add-to-cost-tracker-button').attr('item-slug', slug);
2501 - jQuery('.mainwp-cost-tracker-assistant-add-to-cost-tracker-button').attr('item-type', type);
2502 - jQuery('.mainwp-cost-tracker-assistant-add-to-cost-tracker-button').attr('item-name', installResults.name);
2503 - jQuery('.mainwp-cost-tracker-assistant-add-to-cost-tracker-button').attr('cost-id', installResults.add_to_cost_tracker_id);
2504 - if (installResults.installed_sites != undefined) {
2505 - jQuery('.mainwp-cost-tracker-assistant-add-to-cost-tracker-button').attr('installed-sites', installResults.installed_sites.join(','));
2506 - }
2507 - }
2508 2792 }
2509 - }
2510 2793 };
2511 2794
2512 2795 /**
2513 2796 * Install Plugin/Theme from WP.org.
@@ -2521,92 +2804,86 @@
2521 2804 * @param object siteToInstall Site to install the item to.
2522 2805 *
2523 2806 * @return void
2524 2807 */
2525 -mainwp_install_bulk_start_specific = function (type, url, activatePlugin, overwrite, siteToInstall, slug, installResults) {
2526 - bulkInstallCurrentThreads++;
2808 +let mainwp_install_bulk_start_specific = function (type, url, activatePlugin, overwrite, siteToInstall, slug, installResults) {
2809 + bulkInstallCurrentThreads++;
2527 2810
2528 - siteToInstall.attr('status', 'progress');
2529 - siteToInstall.find('.queue').hide();
2530 - siteToInstall.find('.progress').show();
2531 - var data = mainwp_secure_data({
2532 - action: 'mainwp_installbulkinstallplugintheme',
2533 - type: type,
2534 - url: url,
2535 - activatePlugin: activatePlugin,
2536 - overwrite: overwrite,
2537 - siteId: siteToInstall.attr('siteid')
2538 - });
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 + });
2539 2822
2540 - jQuery.post(ajaxurl, data, function (type, url, activatePlugin, overwrite, siteToInstall) {
2541 - return function (response) {
2542 - siteToInstall.attr('status', 'done');
2543 - siteToInstall.find('.progress').hide();
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 + }
2544 2844
2545 - var statusEl = siteToInstall.find('.status');
2546 - statusEl.show();
2845 + if (_error !== '') {
2846 + statusEl.html('<span data-inverted="" data-position="left center" data-tooltip="' + _error + '"><i class="times red icon"></i></span>');
2847 + }
2547 2848
2548 - var success = false;
2549 - var _error = '';
2550 - if (response.error != undefined) {
2551 - statusEl.html(response.error);
2552 - statusEl.css('color', 'red');
2553 - } else if ((response.ok != undefined) && (response.ok[siteToInstall.attr('siteid')] != undefined)) {
2554 - statusEl.html('<span data-inverted="" data-position="left center" data-tooltip="' + __('Installation completed successfully.', 'mainwp') + '"><i class="check green icon"></i></span>');
2555 - success = true;
2556 - if (installResults.installed_sites == undefined) {
2557 - installResults.installed_sites = [];
2849 + bulkInstallCurrentThreads--;
2850 + bulkInstallDone++;
2851 +
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);
2558 2855 }
2559 - installResults.installed_sites.push(siteToInstall.attr('siteid'));
2560 - } else if ((response.errors != undefined) && (response.errors[siteToInstall.attr('siteid')] != undefined)) {
2561 - _error = response.errors[siteToInstall.attr('siteid')][1];
2562 - } else {
2563 - _error = __('Undefined error occurred. Please try again.', 'mainwp');
2564 - }
2565 -
2566 - if (_error !== '') {
2567 - statusEl.html('<span data-inverted="" data-position="left center" data-tooltip="' + _error + '"><i class="times red icon"></i></span>');
2568 - }
2569 -
2570 - bulkInstallCurrentThreads--;
2571 - bulkInstallDone++;
2572 -
2573 - jQuery('#plugintheme-installation-progress-modal .mainwp-modal-progress').progress('set progress', bulkInstallDone);
2574 - jQuery('#plugintheme-installation-progress-modal .mainwp-modal-progress').find('.label').html(bulkInstallDone + '/' + bulkInstallTotal + ' ' + __('Installed'));
2575 - mainwp_install_bulk_start_next(type, url, activatePlugin, overwrite, slug, installResults);
2576 - }
2577 - }(type, url, activatePlugin, overwrite, siteToInstall), 'json');
2856 + }(type, url, activatePlugin, overwrite, siteToInstall), 'json');
2578 2857 };
2579 2858
2580 2859
2581 -mainwp_install_bulk_you_know_msg = function (type, total) {
2582 - var msg = '';
2583 - if (mainwpParams.installedBulkSettingsManager && mainwpParams.installedBulkSettingsManager == 1) {
2584 - if (type == 'plugin') {
2585 - if (total == 1)
2586 - 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>');
2587 - else
2588 - 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>');
2589 - } else {
2590 - if (total == 1)
2591 - 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>');
2592 - else
2593 - 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>');
2860 +let mainwp_install_bulk_you_know_msg = function (type, total) { // NOSONAR - complex.
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.
2879 + } else if (type == 'theme') {
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.
2594 2884 }
2595 - } else {
2596 - if (type == 'plugin') {
2597 - if (total == 1)
2598 - 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>');
2599 - else
2600 - 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>');
2601 - } else {
2602 - if (total == 1)
2603 - 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>');
2604 - else
2605 - 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>');
2606 - }
2607 - }
2608 - return msg;
2885 + return msg;
2609 2886 }
2610 2887
2611 2888 /**
2612 2889 * Install Plugin/Theme by Upload.
@@ -2616,117 +2893,117 @@
2616 2893 * @param string type Plugin or theme.
2617 2894 *
2618 2895 * @return void
2619 2896 */
2620 -mainwp_upload_bulk = function (type) {
2897 +let mainwp_upload_bulk = function (type) {
2621 2898
2622 - if (type == 'plugins') {
2623 - type = 'plugin';
2624 - } else {
2625 - type = 'theme';
2626 - }
2899 + if (type == 'plugins') {
2900 + type = 'plugin';
2901 + } else {
2902 + type = 'theme';
2903 + }
2627 2904
2628 - var files = [];
2905 + let files = [];
2629 2906
2630 - jQuery(".qq-upload-file").each(function () {
2631 - if (jQuery(this).closest('.file-uploaded-item').hasClass('qq-upload-success')) {
2632 - files.push(jQuery(this).attr('filename'));
2633 - }
2634 - });
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 + });
2635 2912
2636 - if (files.length == 0) {
2637 - if (type == 'plugin') {
2638 - feedback('mainwp-message-zone', __('Please upload at least one plugin to install.', 'mainwp'), 'yellow');
2639 - } else {
2640 - 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;
2641 2920 }
2642 - return;
2643 - }
2644 2921
2645 - var data = mainwp_secure_data({
2646 - action: 'mainwp_preparebulkuploadplugintheme',
2647 - type: type,
2648 - selected_by: jQuery('#select_by').val()
2649 - });
2922 + let data = mainwp_secure_data({
2923 + action: 'mainwp_preparebulkuploadplugintheme',
2924 + type: type,
2925 + selected_by: jQuery('input[name="select_by"]').val()
2926 + });
2650 2927
2651 - var 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>';
2652 2929
2653 - if (jQuery('#select_by').val() == 'site') {
2654 - var selected_sites = [];
2655 - jQuery("input[name='selected_sites[]']:checked").each(function () {
2656 - selected_sites.push(jQuery(this).val());
2657 - });
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 + });
2658 2935
2659 - if (selected_sites.length == 0) {
2660 - feedback('mainwp-message-zone', __('Please select at least one website or a group or client.', 'mainwp'), 'yellow');
2661 - return;
2662 - }
2663 - data['selected_sites[]'] = selected_sites;
2664 - } else if (jQuery('#select_by').val() == 'client') {
2665 - var selected_clients = [];
2666 - jQuery("input[name='selected_clients[]']:checked").each(function () {
2667 - selected_clients.push(jQuery(this).val());
2668 - });
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 + });
2669 2946
2670 - if (selected_clients.length == 0) {
2671 - feedback('mainwp-message-zone', __('Please select at least one website or a group or client.', 'mainwp'), 'yellow');
2672 - 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;
2673 2962 }
2674 - data['selected_clients[]'] = selected_clients;
2675 - } else {
2676 - var selected_groups = [];
2677 - jQuery("input[name='selected_groups[]']:checked").each(function () {
2678 - selected_groups.push(jQuery(this).val());
2679 - });
2680 - if (selected_groups.length == 0) {
2681 - feedback('mainwp-message-zone', __('Please select at least one website or a group or client.', 'mainwp'), 'yellow');
2682 - return;
2683 - }
2684 - data['selected_groups[]'] = selected_groups;
2685 - }
2686 2963
2687 - data['files[]'] = files;
2964 + data['files[]'] = files;
2688 2965
2689 - jQuery('#plugintheme-installation-queue').html(placeholder);
2966 + jQuery('#plugintheme-installation-queue').html(placeholder);
2690 2967
2691 - jQuery.post(ajaxurl, data, function (type, files, activatePlugin, overwrite) {
2692 - return function (response) {
2693 - var installQueue = '';
2694 - bulkInstallTotal = 0;
2695 - 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;
2696 2973
2697 - installQueue += '<div class="ui middle aligned selection divided list">';
2974 + installQueue += '<div class="ui middle aligned selection divided list">';
2698 2975
2699 - for (var siteId in response.sites) {
2700 - var site = response.sites[siteId];
2976 + for (let siteId in response.sites) {
2977 + let site = response.sites[siteId];
2701 2978
2702 - installQueue +=
2703 - '<div class="siteBulkInstall item" siteid="' + siteId + '" status="queue">' +
2704 - '<div class="right floated content">' +
2705 - '<span class="queue" data-inverted="" data-position="left center" data-tooltip="' + __('Queued', 'mainwp') + '"><i class="clock outline icon"></i></span>' +
2706 - '<span class="progress" data-inverted="" data-position="left center" data-tooltip="' + __('Installing...', 'mainwp') + '" style="display:none"><i class="notched circle loading icon"></i></span>' +
2707 - '<span class="status"></span>' +
2708 - '</div>' +
2709 - '<div class="content">' + mainwp_links_visit_site_and_admin('', siteId) + ' ' + '<a href="' + site['url'] + '">' + site['name'].replace(/\\(.)/mg, "$1") + '</a></div>' +
2710 - '<div class="installation-entries"></div>' +
2711 - '</div>';
2712 - bulkInstallTotal++;
2713 - }
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 + }
2714 2991
2715 - installQueue += '</div>';
2992 + installQueue += '</div>';
2716 2993
2717 - jQuery('#plugintheme-installation-queue').html(installQueue);
2994 + jQuery('#plugintheme-installation-queue').html(installQueue);
2718 2995
2719 - jQuery('#plugintheme-installation-progress-modal .mainwp-modal-progress').progress({ value: 0, total: bulkInstallTotal });
2720 - mainwp_upload_bulk_start_next(type, response.urls, activatePlugin, overwrite);
2721 - }
2722 - }(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');
2723 3000
2724 - jQuery('#plugintheme-installation-progress-modal').modal('setting', 'closable', false).modal('show');
3001 + jQuery('#plugintheme-installation-progress-modal').modal('setting', 'closable', false).modal('show');
2725 3002
2726 - jQuery('.qq-upload-list').html(''); // empty files list!
3003 + jQuery('.qq-upload-list').html(''); // empty files list!
2727 3004
2728 - return false;
3005 + return false;
2729 3006 };
2730 3007
2731 3008 /**
2732 3009 * Install Plugin/Theme by Upload.
@@ -2739,52 +3016,56 @@
2739 3016 * @param bool overwrite Determines if the item should overwrite exisitng version.
2740 3017 *
2741 3018 * @return void
2742 3019 */
2743 -mainwp_upload_bulk_start_next = function (type, urls, activatePlugin, overwrite) {
2744 - while ((siteToInstall = jQuery('.siteBulkInstall[status="queue"]:first')) && (siteToInstall.length > 0) && (bulkInstallCurrentThreads < bulkInstallMaxThreads)) {
2745 - mainwp_upload_bulk_start_specific(type, urls, activatePlugin, overwrite, siteToInstall);
2746 - }
3020 +let mainwp_upload_bulk_start_next = function (type, urls, activatePlugin, overwrite) {
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 + }
2747 3024
2748 - if ((siteToInstall.length == 0) && (bulkInstallCurrentThreads == 0)) {
2749 - var data = mainwp_secure_data({
2750 - action: 'mainwp_cleanbulkuploadplugintheme'
2751 - });
2752 - jQuery.post(ajaxurl, data, function () { });
2753 - var msg = mainwp_install_bulk_you_know_msg(type, jQuery('#bulk_upload_info').attr('number-files'));
3025 + if ((siteToInstall.length == 0) && (bulkInstallCurrentThreads == 0)) { // NOSONAR - modified outside the function.
3026 + let data = mainwp_secure_data({
3027 + action: 'mainwp_cleanbulkuploadplugintheme',
3028 + });
2754 3029
2755 - jQuery('#bulk_upload_info').html('<div class="mainwp-notice mainwp-notice-blue">' + msg + '</div>');
3030 + jQuery.post(ajaxurl, data, function () {
3031 + jQuery('.file-uploaded-item.qq-upload-completed').remove();
3032 + });
2756 3033
2757 - if (jQuery('.mainwp_cost_tracker_assistant_installed_items').length > 0) { // to support add to cost tracker pro.
2758 - var cost_tracker_items = [];
2759 - var cost_tracker_check_slugs = [];
2760 - jQuery('.mainwp_cost_tracker_assistant_installed_items').each(function () {
2761 - var slug = jQuery(this).attr('item-slug');
2762 - var items_slug = {};
2763 - if (!cost_tracker_check_slugs.includes(slug)) {
2764 - cost_tracker_check_slugs.push(slug);
2765 - var siteids = [];
2766 - jQuery('.mainwp_cost_tracker_assistant_installed_items[item-slug="' + slug + '"]').each(function () {
2767 - siteids.push(jQuery(this).attr('item-siteid'));
2768 - });
2769 - items_slug.slug = slug;
2770 - items_slug.name = jQuery(this).attr('item-name');
2771 - items_slug.type = jQuery(this).attr('item-type');
2772 - items_slug.cost_id = jQuery(this).attr('cost-id');
2773 - items_slug.sites_ids = siteids;
2774 - cost_tracker_items.push(items_slug);
3034 + let msg = mainwp_install_bulk_you_know_msg(type, jQuery('#bulk_upload_info').attr('number-files'));
3035 +
3036 + jQuery('#bulk_upload_info').html('<div class="bui blue message">' + msg + '</div>');
3037 +
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 + }
2775 3066 }
2776 - });
2777 -
2778 - if (cost_tracker_items.length > 0) {
2779 - jQuery('.mainwp-cost-tracker-assistant-add-buttons-wrapper').html('');
2780 - var multiAddTo = cost_tracker_items.length > 1 ? 1 : 0;
2781 - cost_tracker_items.forEach(item => {
2782 - 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>');
2783 - });
2784 - }
2785 3067 }
2786 - }
2787 3068 };
2788 3069
2789 3070 /**
2790 3071 * Install Plugin/Theme by Upload.
@@ -2798,194 +3079,705 @@
2798 3079 * @param object siteToInstall Site to install the item to.
2799 3080 *
2800 3081 * @return void
2801 3082 */
2802 -mainwp_upload_bulk_start_specific = function (type, urls, activatePlugin, overwrite, siteToInstall) {
2803 - bulkInstallCurrentThreads++;
2804 - siteToInstall.attr('status', 'progress');
3083 +let mainwp_upload_bulk_start_specific = function (type, urls, activatePlugin, overwrite, siteToInstall) {
3084 + bulkInstallCurrentThreads++;
3085 + siteToInstall.attr('status', 'progress');
2805 3086
2806 - siteToInstall.find('.queue').hide();
2807 - siteToInstall.find('.progress').show();
3087 + siteToInstall.find('.queue').hide();
3088 + siteToInstall.find('.progress').show();
2808 3089
2809 - var data = mainwp_secure_data({
2810 - action: 'mainwp_installbulkuploadplugintheme',
2811 - type: type,
2812 - urls: urls,
2813 - activatePlugin: activatePlugin,
2814 - overwrite: overwrite,
2815 - siteId: siteToInstall.attr('siteid')
2816 - });
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 + });
2817 3098
2818 - jQuery.post(ajaxurl, data, function (type, urls, activatePlugin, overwrite, siteToInstall) {
2819 - return function (response) {
2820 - siteToInstall.attr('status', 'done');
2821 - siteToInstall.find('.progress').hide();
2822 - var statusEl = siteToInstall.find('.status');
2823 - var siteid = siteToInstall.attr('siteid');
2824 - 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();
2825 3106
2826 - if (response.error != undefined) {
2827 - statusEl.html(response.error);
2828 - statusEl.css('color', 'red');
2829 - } else if ((response.ok != undefined) && (response.ok[siteid] != undefined)) {
2830 - var results = '';
2831 - if ((response.results != undefined) && (response.results[siteid] != undefined)) {
2832 - entries = Object.entries(response.results[siteid]);
2833 - results += '<div class="ui tiny middle aligned selection list">';
2834 - for (var entry of entries) {
2835 - 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>';
2836 - }
2837 - 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);
2838 3136 }
2839 - jQuery('div[siteId="' + siteid + '"] .installation-entries').html(results);
2840 - if (response.cost_tracker_installed_info != undefined) { // to support add to cost tracker pro.
2841 - 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 + }
2842 3158 }
2843 - statusEl.html('<span data-inverted="" data-position="left center" data-tooltip="' + __('Installation completed successfully.', 'mainwp') + '"><i class="check green icon"></i></span>');
2844 - } else if ((response.errors != undefined) && (response.errors[siteid] != undefined)) {
2845 - statusEl.html('<span data-inverted="" data-position="left center" data-tooltip="' + response.errors[siteid][1] + '"><i class="times red icon"></i></span>');
2846 - } else {
2847 - 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>');
2848 - }
2849 3159
2850 - bulkInstallCurrentThreads--;
2851 - bulkInstallDone++;
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 + '/' + bulkInstallTotal + ' ' + __('Installed'));
2854 - 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')
2855 3354 }
2856 - }(type, urls, activatePlugin, overwrite, siteToInstall), 'json');
2857 -};
2858 3355
2859 -jQuery(document).ready(function ($) {
2860 - jQuery(document).on('click', '.open-plugin-details-modal', function () {
2861 - var itemDetail = this;
3356 + jQuery(md).find('.actions .col-left').html('');
3357 + jQuery(md).find('.actions .col-right').html('');
2862 3358
2863 - var openwpp = jQuery(this).attr('open-wpplugin');
2864 - var openwpp_site = '';
2865 - if (typeof openwpp != "undefined" && 'yes' == openwpp) {
2866 - var findNext = jQuery(this).closest('tr').next().find('tr[open-wpplugin-siteid]');
2867 - if (findNext.length > 0) {
2868 - openwpp_site = '&wpplugin=' + jQuery(findNext).attr('open-wpplugin-siteid');
2869 - }
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;
2870 3370 }
2871 - $('#mainwp-plugin-details-modal').modal({
2872 - onHide: function () {
2873 - },
2874 - onShow: function () {
2875 - $('#mainwp-plugin-details-modal').find('.ui.embed').embed({
2876 - source: 'WP',
2877 - url: $(itemDetail).attr('href') + openwpp_site,
2878 - });
2879 - }
2880 - }).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 +
2881 3626 return false;
2882 - });
2883 -});
3627 +}
2884 3628
2885 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 +
2886 3655 /**
2887 3656 * Install check plugins.
2888 3657 *
2889 3658 */
2890 3659
2891 -mainwp_install_check_plugin_prepare = function (slug) {
2892 - var selected = jQuery("input[name='install_checker[]']:checked");
2893 - if (selected.length == 0) {
2894 - feedback('mainwp-message-zone-install', __('Please select website to install plugin.'), 'yellow');
2895 - return;
2896 - } else {
2897 - selected.each(function () {
2898 - 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,
2899 3675 });
2900 - }
2901 - jQuery('#mainwp-install-check-btn').addClass('disabled');
2902 - jQuery('#mainwp-message-zone-install').html('<i class="notched circle loading icon"></i> ').show();
2903 - var data = mainwp_secure_data({
2904 - action: 'mainwp_preparebulkinstallcheckplugin',
2905 - slug: slug,
2906 - });
2907 - jQuery.post(ajaxurl, data, function (response) {
2908 - jQuery('#mainwp-message-zone-install').html('').hide();
2909 - mainwp_install_check_plugin_start_next(response.url);
2910 - }, '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');
2911 3680 };
2912 3681
2913 -mainwp_install_check_plugin_start_next = function (url) {
2914 - while ((siteToInstall = jQuery('.siteBulkInstall[status="queue"]:first')) && (siteToInstall.length > 0) && (bulkInstallCurrentThreads < bulkInstallMaxThreads)) {
2915 - mainwp_install_check_plugin_start_specific(url, siteToInstall);
2916 - }
3682 +let mainwp_install_check_plugin_start_next = function (url) {
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 + }
2917 3686 };
2918 3687
2919 -mainwp_install_check_plugin_start_specific = function (url, siteToInstall) {
2920 - bulkInstallCurrentThreads++;
3688 +let mainwp_install_check_plugin_start_specific = function (url, siteToInstall) {
3689 + bulkInstallCurrentThreads++;
2921 3690
2922 - siteToInstall.attr('status', 'progress');
2923 - siteToInstall.find('.queue').hide();
2924 - siteToInstall.find('.progress').show();
3691 + siteToInstall.attr('status', 'progress');
3692 + siteToInstall.find('.queue').hide();
3693 + siteToInstall.find('.progress').show();
2925 3694
2926 - var data = mainwp_secure_data({
2927 - action: 'mainwp_installbulkinstallplugintheme',
2928 - type: 'plugin',
2929 - url: url,
2930 - activatePlugin: 'true',
2931 - siteId: siteToInstall.attr('siteid')
2932 - });
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 + });
2933 3702
2934 - jQuery.post(ajaxurl, data, function (url, siteToInstall) {
2935 - return function (response) {
2936 - siteToInstall.attr('status', 'done');
2937 - 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();
2938 3707
2939 - var statusEl = siteToInstall.find('.status');
2940 - statusEl.show();
3708 + let statusEl = siteToInstall.find('.status');
3709 + statusEl.show();
2941 3710
2942 - if (response.error != undefined) {
2943 - statusEl.html(response.error);
2944 - statusEl.css('color', 'red');
2945 - } else if ((response.ok != undefined) && (response.ok[siteToInstall.attr('siteid')] != undefined)) {
2946 - statusEl.html('<span data-inverted="" data-position="left center" data-tooltip="' + __('Installation completed successfully.', 'mainwp') + '"><i class="check green icon"></i></span>');
2947 - } else if ((response.errors != undefined) && (response.errors[siteToInstall.attr('siteid')] != undefined)) {
2948 - statusEl.html('<span data-inverted="" data-position="left center" data-tooltip="' + response.errors[siteToInstall.attr('siteid')][1] + '"><i class="times red icon"></i></span>');
2949 - } else {
2950 - 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>');
2951 - }
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 + }
2952 3721
2953 - bulkInstallCurrentThreads--;
2954 - bulkInstallDone++;
2955 - jQuery('#plugintheme-installation-progress-modal .mainwp-modal-progress').progress('set progress', bulkInstallDone);
2956 - jQuery('#plugintheme-installation-progress-modal .mainwp-modal-progress').find('.label').html(bulkInstallDone + '/' + bulkInstallTotal + ' ' + __('Installed'));
2957 - mainwp_install_check_plugin_start_next(url);
2958 - }
2959 - }(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');
2960 3729 };
2961 3730
3731 +function isUrl(url) {
3732 + try {
3733 + new URL(url);
3734 + return true;
3735 + } catch (e) {
3736 + console.log(e);
3737 + }
3738 + return false;
3739 +}
2962 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 +}
2963 3753
2964 -/**
2965 - * Utility
2966 - */
2967 -function isUrl(s) {
2968 - var regexp = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-/]))?/;
2969 - return regexp.test(s);
3754 +function setVisible(what, vis) {
3755 + if (vis) {
3756 + jQuery(what).show();
3757 + } else {
3758 + jQuery(what).hide();
3759 + }
2970 3760 }
2971 -function setVisible(what, vis) {
2972 - if (vis) {
2973 - jQuery(what).show();
2974 - } else {
2975 - jQuery(what).hide();
2976 - }
3761 +
3762 +const mainwp_scrollToElement = () => {
3763 + jQuery('html,body').animate({
3764 + scrollTop: 0
3765 + }, 1000);
3766 +
3767 + return false;
2977 3768 }
3769 +
2978 3770 function setHtml(what, text, ptag) {
2979 - if (typeof ptag == "undefined")
2980 - ptag = true;
3771 + if (ptag === undefined)
3772 + ptag = true;
2981 3773
2982 - setVisible(what, true);
2983 - if (ptag)
2984 - jQuery(what).html('<span>' + text + '</span>');
2985 - else
2986 - jQuery(what).html(text);
2987 - 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.
2988 3780 }
2989 3781
2990 3782
2991 3783 /**
@@ -2990,281 +3782,304 @@
2990 3782
2991 3783 /**
2992 3784 * Notes
2993 3785 */
2994 -jQuery(document).ready(function () {
3786 +jQuery(function () {
2995 3787
2996 - jQuery(document).on('click', '#mainwp-notes-cancel', function () {
2997 - jQuery('#mainwp-notes-status').html('');
2998 - jQuery('#mainwp-notes-status').removeClass('red green');
2999 - mainwp_notes_hide();
3000 - return false;
3001 - });
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 + });
3002 3794
3003 - jQuery(document).on('click', '#mainwp-notes-save', function () {
3004 - var which = jQuery('#mainwp-which-note').val();
3005 - if (which == 'site') {
3006 - mainwp_notes_site_save();
3007 - } else if (which == 'theme') {
3008 - mainwp_notes_theme_save();
3009 - } else if (which == 'plugin') {
3010 - mainwp_notes_plugin_save()
3011 - } else if (which == 'client') {
3012 - mainwp_notes_client_save()
3013 - }
3014 - var newnote = jQuery('#mainwp-notes-note').val();
3015 - jQuery('#mainwp-notes-html').html(newnote);
3016 - return false;
3017 - });
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 + });
3018 3808
3019 - jQuery(document).on('click', '.mainwp-edit-site-note', function () {
3020 - var id = jQuery(this).attr('id').substr(13);
3021 - var note = jQuery('#mainwp-notes-' + id + '-note').html();
3022 - jQuery('#mainwp-notes-html').html(note == '' ? __('No saved notes. Click the Edit button to edit site notes.') : note);
3023 - jQuery('#mainwp-notes-note').val(note);
3024 - jQuery('#mainwp-notes-websiteid').val(id);
3025 - jQuery('#mainwp-which-note').val('site'); // to fix conflict.
3026 - mainwp_notes_show();
3027 - return false;
3028 - });
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 + });
3029 3822
3030 - jQuery(document).on('click', '#mainwp-notes-edit', function () {
3031 - jQuery('#mainwp-notes-html').hide();
3032 - jQuery('#mainwp-notes-editor').show();
3033 - jQuery(this).hide();
3034 - jQuery('#mainwp-notes-save').show();
3035 - jQuery('#mainwp-notes-status').html('');
3036 - jQuery('#mainwp-notes-status').removeClass('red green');
3037 - return false;
3038 - });
3039 - jQuery('#redirectForm').trigger("submit");
3040 - if (jQuery('div.ui.open-site-close-window').length > 0) {
3041 - setTimeout(function () {
3042 - window.close()
3043 - }, 3000);
3044 - }
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 + }
3045 3838 });
3046 3839
3047 -mainwp_notes_show = function (reloadClose) {
3048 - if (reloadClose) {
3049 - jQuery('#mainwp-notes-modal').modal({
3050 - onHide: function () {
3051 - window.location.href = location.href
3052 - }
3053 - }).modal('show');
3054 - } else {
3055 - jQuery('#mainwp-notes-modal').modal({ closable: false }).modal('show');
3056 - }
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 + }
3057 3850
3058 - jQuery('#mainwp-notes-html').show();
3059 - jQuery('#mainwp-notes-editor').hide();
3060 - jQuery('#mainwp-notes-save').hide();
3061 - 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();
3062 3855 };
3063 -mainwp_notes_hide = function () {
3064 - jQuery('#mainwp-notes-modal').modal('hide');
3856 +let mainwp_notes_hide = function () {
3857 + jQuery('#mainwp-notes-modal').modal('hide');
3065 3858 };
3066 -mainwp_notes_site_save = function () {
3067 - var normalid = jQuery('#mainwp-notes-websiteid').val();
3068 - var newnote = jQuery('#mainwp-notes-note').val();
3069 - newnote = newnote.replace(/(?:\r\n|\r|\n)/g, '<br>');
3070 - var data = mainwp_secure_data({
3071 - action: 'mainwp_notes_save',
3072 - websiteid: normalid,
3073 - note: newnote
3074 - });
3859 +let mainwp_notes_site_save = function () {
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 + });
3075 3868
3076 - 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();
3077 3870
3078 - jQuery.post(ajaxurl, data, function (response) {
3079 - if (response.error != undefined) {
3080 - jQuery('#mainwp-notes-status').html(response.error).addClass('red');
3081 - } else if (response.result == 'SUCCESS') {
3082 - jQuery('#mainwp-notes-status').html(__('Note saved successfully.')).addClass('green');
3083 - if (jQuery('#mainwp-notes-' + normalid + '-note').length > 0) {
3084 - jQuery('#mainwp-notes-' + normalid + '-note').html(jQuery('#mainwp-notes-note').val());
3085 - }
3086 - } else {
3087 - jQuery('#mainwp-notes-status').html(__('Undefined error occured while saving your note!')).addClass('red');
3088 - }
3089 - }, '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');
3090 3884
3091 - setTimeout(function () {
3092 - jQuery('#mainwp-notes-status').fadeOut(300);
3093 - }, 3000);
3885 + setTimeout(function () {
3886 + jQuery('#mainwp-notes-status').fadeOut(300);
3887 + }, 3000);
3094 3888
3095 - jQuery('#mainwp-notes-html').show();
3096 - jQuery('#mainwp-notes-editor').hide();
3097 - jQuery('#mainwp-notes-save').hide();
3098 - 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();
3099 3893
3100 3894 };
3101 3895
3102 -getErrorMessage = function (pError, msgOnly) {
3103 - if (pError.message == 'HTTPERROR') {
3104 - return __('HTTP error') + '! ' + pError.extra;
3105 - } else if (pError.message == 'NOMAINWP' || pError == 'NOMAINWP') {
3106 - return mainwp_js_get_error_not_detected_connect();
3107 - } else if (pError.message == 'ERROR') {
3108 - return 'ERROR' + ((pError.extra != '') && (pError.extra != undefined) ? ': ' + pError.extra : '');
3109 - } else if (pError.message == 'WPERROR') {
3110 - var extrMsg = (pError.extra != '') && (pError.extra != undefined) ? pError.extra : '';
3111 - if (msgOnly != undefined && msgOnly && extrMsg != '') {
3112 - 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;
3113 3913 } else {
3114 - return __('ERROR on the child site') + ': ' + extrMsg;
3914 + return pError;
3115 3915 }
3116 -
3117 - } else if (pError.message != undefined && pError.message != '') {
3118 - return pError.message;
3119 - } else {
3120 - return pError;
3121 - }
3122 3916 };
3123 3917
3124 -getErrorMessageInfo = function (repError, outputType) {
3125 - var msg = '';
3126 - var 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>';
3127 3921
3128 - if (repError.errorCode != undefined && repError.errorCode == 'SUSPENDED_SITE') {
3129 - msg = __('Suspended site.');
3130 - msgUI = '<span data-inverted="" data-position="left center" data-tooltip="' + __('Suspended site.') + '"><i class="pause circular yellow inverted icon"></i></span>';
3131 - }
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 + }
3132 3926
3133 - if (repError.errorCode != undefined && repError.errorCode == 'MAINWP_NOTICE') {
3134 - if (repError.message != undefined) {
3135 - msg = repError.message;
3136 - 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 + }
3137 3932 }
3138 - }
3139 3933
3140 - if (msg == '') {
3141 - msg = getErrorMessage(repError);
3934 + if (msg == '') {
3935 + msg = getErrorMessage(repError);
3142 3936
3143 - if (repError.message == 'NOMAINWP' || repError == 'NOMAINWP') {
3144 - 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 + }
3145 3944 }
3146 3945
3147 3946 if (msg != '') {
3148 - 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 + }
3149 3952 }
3150 - }
3151 3953
3152 - if (msg != '') {
3153 - if (outputType != undefined && outputType == 'ui') {
3154 - return msgUI;
3155 - } else {
3156 - return msg;
3157 - }
3158 - }
3159 -
3160 - return repError;
3954 + return repError;
3161 3955 }
3162 3956
3163 -dateToHMS = function (date) {
3164 - if (mainwpParams != undefined && mainwpParams['time_format'] != undefined) {
3165 - var time = moment(date);
3166 - var format = mainwpParams['time_format'];
3167 - format = format.replace('g', 'h');
3168 - format = format.replace('i', 'mm');
3169 - format = format.replace('s', 'ss');
3170 - format = format.replace('F', 'MMMM');
3171 - format = format.replace('j', 'D');
3172 - format = format.replace('Y', 'YYYY');
3173 - return time.format(format);
3174 - }
3175 - var h = date.getHours();
3176 - var m = date.getMinutes();
3177 - var s = date.getSeconds();
3178 - 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);
3179 3973 };
3180 -appendToDiv = function (pSelector, pText, pScrolldown, pShowTime) {
3181 - if (pScrolldown == undefined)
3182 - pScrolldown = true;
3183 - if (pShowTime == undefined)
3184 - pShowTime = true;
3974 +globalThis.appendToDiv = function (pSelector, pText, pScrolldown, pShowTime) {
3975 + if (pScrolldown == undefined)
3976 + pScrolldown = true;
3977 + if (pShowTime == undefined)
3978 + pShowTime = true;
3185 3979
3186 - var theDiv = jQuery(pSelector);
3187 - theDiv.append('<br />' + (pShowTime ? dateToHMS(new Date()) + ' ' : '') + pText);
3188 - if (pScrolldown)
3189 - 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);
3190 3984 };
3191 3985
3192 3986 jQuery.fn.exists = function () {
3193 - return (this.length !== 0);
3987 + return (this.length !== 0);
3194 3988 };
3195 3989
3196 3990
3197 -function __(text, _var1, _var2, _var3) {
3198 - if (text == undefined || text == '')
3199 - return text;
3200 - var strippedText = text.replace(/ /g, '_');
3201 - strippedText = strippedText.replace(/[^A-Za-z0-9_]/g, '');
3991 +globalThis.MainWP = globalThis.MainWP || {};
3992 +globalThis.MainWP.I18n = globalThis.MainWP.I18n || {};
3202 3993
3203 - if (strippedText == '')
3204 - 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 + }
3205 3998
3206 - if (mainwpTranslations == undefined)
3207 - return text.replace('%1', _var1).replace('%2', _var2).replace('%3', _var3);
3208 - if (mainwpTranslations[strippedText] == undefined)
3209 - 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, '_');
3210 4001
3211 - 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 + };
3212 4028 }
3213 4029
3214 -mainwp_secure_data = function (data, includeDts) {
3215 - if (data['action'] == undefined)
3216 - return data;
4030 +globalThis.mainwp_secure_data = function (data, includeDts) {
4031 + if (data['action'] == undefined)
4032 + return data;
3217 4033
3218 - 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);
3219 4040 return data;
3220 -
3221 - data['security'] = security_nonces[data['action']];
3222 - if (includeDts)
3223 - data['dts'] = Math.round(new Date().getTime() / 1000);
3224 - return data;
3225 4041 };
3226 4042
3227 4043
3228 -mainwp_uid = function () {
3229 - // always start with a letter (for DOM friendlyness)
3230 - var idstr = String.fromCharCode(Math.floor((Math.random() * 25) + 65));
3231 - do {
3232 - // between numbers and characters (48 is 0 and 90 is Z (42-48 = 90)
3233 - var ascicode = Math.floor((Math.random() * 42) + 48);
3234 - if (ascicode < 58 || ascicode > 64) {
3235 - // exclude all chars between : (58) and @ (64)
3236 - idstr += String.fromCharCode(ascicode);
3237 - }
3238 - } 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);
3239 4055
3240 - return (idstr);
4056 + return (idstr);
3241 4057 };
3242 4058
3243 -scrollToElement = function () {
3244 - jQuery('html,body').animate({
3245 - scrollTop: 0
3246 - }, 1000);
4059 +globalThis.scrollToElement = function () {
4060 + jQuery('html,body').animate({
4061 + scrollTop: 0
4062 + }, 1000);
3247 4063
3248 - return false;
4064 + return false;
3249 4065 };
3250 4066
3251 -jQuery(document).ready(function () {
3252 - jQuery('#backup_filename').on('keypress', function (e) {
3253 - var chr = String.fromCharCode(e.which);
3254 - return ("$^&*/".indexOf(chr) < 0);
3255 - });
3256 - jQuery('#backup_filename').on('change', function () {
3257 - var value = jQuery(this).val();
3258 - var notAllowed = ['$', '^', '&', '*', '/'];
3259 - for (var i = 0; i < notAllowed.length; i++) {
3260 - var char = notAllowed[i];
3261 - if (value.indexOf(char) >= 0) {
3262 - value = value.replace(new RegExp('\\' + char, 'g'), '');
3263 - jQuery(this).val(value);
3264 - }
3265 - }
3266 - });
4067 +jQuery(function () {
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 + });
3267 4082 });
3268 4083
3269 4084 /*
3270 4085 * Server Info
@@ -3269,960 +4084,1136 @@
3269 4084 /*
3270 4085 * Server Info
3271 4086 */
3272 4087
3273 -serverinfo_prepare_download_info = function (communi) {
3274 - var report = "";
3275 - jQuery('.mainwp-system-info-table thead, .mainwp-system-info-table tbody').each(function () {
3276 - var td_len = [35, 55, 45, 12, 12];
3277 - var th_count = 0;
3278 - var i;
3279 - if (jQuery(this).is('thead')) {
3280 - i = 0;
3281 - report = report + "\n### ";
3282 - th_count = jQuery(this).find('th:not(".mwp-not-generate-row")').length;
3283 - jQuery(this).find('th:not(".mwp-not-generate-row")').each(function () {
3284 - var len = td_len[i];
3285 - if (i == 0 || i == th_count - 1)
3286 - len = len - 4;
3287 - report = report + jQuery.mwp_strCut(jQuery(this).text().trim(), len, ' ');
3288 - i++;
3289 - });
3290 - report = report + " ###\n\n";
3291 - } else {
3292 - jQuery('tr', jQuery(this)).each(function () {
3293 - if (communi && jQuery(this).hasClass('mwp-not-generate-row'))
3294 - return;
3295 - i = 0;
3296 - jQuery(this).find('td:not(".mwp-not-generate-row")').each(function () {
3297 - if (jQuery(this).hasClass('mwp-hide-generate-row')) {
3298 - report = report + jQuery.mwp_strCut(' ', td_len[i], ' ');
3299 - i++;
3300 - return;
3301 - }
3302 - report = report + jQuery.mwp_strCut(jQuery(this).text().trim(), td_len[i], ' ');
3303 - i++;
3304 - });
3305 - report = report + "\n";
3306 - });
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 + });
3307 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:');
3308 4134 }
3309 - });
4135 + return false;
4136 +}
3310 4137
3311 - try {
3312 - if (communi) {
3313 - 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();
3314 4142 }
3315 - jQuery("#download-server-information textarea").val(report).trigger("select");
3316 - } catch (e) {
3317 - console.log('Error:');
3318 - }
3319 - return false;
4143 +
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 + }
4151 +
4152 + let communityValue = element.attr('data-community-value');
4153 + if (communi && typeof communityValue !== 'undefined') {
4154 + return communityValue;
4155 + }
4156 +
4157 + return element.text().trim();
3320 4158 }
3321 4159
3322 4160 jQuery(document).on('click', '#mainwp-download-system-report', function () {
3323 - serverinfo_prepare_download_info(false);
3324 - var server_info = jQuery('#download-server-information textarea').val();
3325 - var blob = new Blob([server_info], { type: "text/plain;charset=utf-8" });
3326 - saveAs(blob, "mainwp-system-report.txt");
3327 - return false;
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;
3328 4166 });
3329 -
3330 -jQuery(document).on('click', '#mainwp-copy-meta-system-report', function () {
3331 - jQuery("#download-server-information").slideDown(); // to able to select and copy
3332 - serverinfo_prepare_download_info(true);
3333 - jQuery("#download-server-information").slideUp();
3334 - try {
3335 - var successful = document.execCommand('copy');
3336 - var msg = successful ? 'successful' : 'unsuccessful';
3337 - console.log('Copying text command was ' + msg);
3338 - } catch (err) {
3339 - console.log('Oops, unable to copy');
3340 - }
3341 - return false;
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;
3342 4173 });
3343 4174
3344 4175
3345 4176 jQuery.mwp_strCut = function (i, l, s, w) {
3346 - var o = i.toString();
3347 - if (!s) {
3348 - s = '0';
3349 - }
3350 - while (o.length < parseInt(l)) {
3351 - // empty
3352 - if (w == 'undefined') {
3353 - o = s + o;
3354 - } else {
3355 - o = o + s;
4177 + let o = i.toString();
4178 + if (!s) {
4179 + s = '0';
3356 4180 }
3357 - }
3358 - 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;
3359 4190 };
3360 4191
3361 -updateExcludedFolders = function () {
3362 - var excludedBackupFiles = jQuery('#excludedBackupFiles').html();
3363 - 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);
3364 4195
3365 - var excludedCacheFiles = jQuery('#excludedCacheFiles').html();
3366 - jQuery('#mainwp-kcl-content').val(excludedCacheFiles == undefined ? '' : excludedCacheFiles);
4196 + let excludedCacheFiles = jQuery('#excludedCacheFiles').html();
4197 + jQuery('#mainwp-kcl-content').val(excludedCacheFiles == undefined ? '' : excludedCacheFiles);
3367 4198
3368 - var excludedNonWPFiles = jQuery('#excludedNonWPFiles').html();
3369 - jQuery('#mainwp-nwl-content').val(excludedNonWPFiles == undefined ? '' : excludedNonWPFiles);
4199 + let excludedNonWPFiles = jQuery('#excludedNonWPFiles').html();
4200 + jQuery('#mainwp-nwl-content').val(excludedNonWPFiles == undefined ? '' : excludedNonWPFiles);
3370 4201 };
3371 4202
3372 4203
3373 4204 jQuery(document).on('click', '.mainwp-events-notice-dismiss', function () {
3374 - var notice = jQuery(this).attr('notice');
3375 - jQuery(this).closest('.ui.message').fadeOut(500);
3376 - var data = mainwp_secure_data({
3377 - action: 'mainwp_events_notice_hide',
3378 - notice: notice
3379 - });
3380 - jQuery.post(ajaxurl, data, function () {
3381 - });
3382 - 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;
3383 4214 });
3384 4215
3385 4216 // Turn On child plugin auto update
3386 4217 jQuery(document).on('click', '#mainwp_btn_autoupdate_and_trust', function () {
3387 - jQuery(this).attr('disabled', 'true');
3388 - var data = mainwp_secure_data({
3389 - action: 'mainwp_autoupdate_and_trust_child'
3390 - });
3391 - jQuery.post(ajaxurl, data, function (res) {
3392 - if (res == 'ok') {
3393 - location.reload(true);
3394 - } else {
3395 - jQuery(this).prop("disabled", false);
3396 - }
3397 - });
3398 - 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;
3399 4230 });
3400 4231
3401 4232 // Hide installation warning
3402 4233 jQuery(document).on('click', '#remove-mainwp-installation-warning', function () {
3403 - jQuery(this).closest('.ui.message').fadeOut("slow");
3404 - var data = mainwp_secure_data({
3405 - action: 'mainwp_installation_warning_hide'
3406 - });
3407 - jQuery.post(ajaxurl, data, function () { });
3408 - 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;
3409 4240 });
3410 4241
3411 4242 jQuery(document).on('click', '.mainwp-notice-hide', function () {
3412 - jQuery(this).closest('.ui.message').fadeOut("slow");
3413 - return false;
4243 + jQuery(this).closest('.ui.message').fadeOut("slow");
4244 + return false;
3414 4245 });
3415 4246
3416 4247 // Hide after installtion notices (PHP version, Trust MainWP Child, Multisite Warning and OpenSSL warning)
3417 4248 jQuery(document).on('click', '.mainwp-notice-dismiss', function () {
3418 - var notice_id = jQuery(this).attr('notice-id');
3419 - jQuery(this).closest('.ui.message').fadeOut("slow");
3420 - var data = {
3421 - action: 'mainwp_notice_status_update'
3422 - };
3423 - data['notice_id'] = notice_id;
3424 - jQuery.post(ajaxurl, mainwp_secure_data(data), function () { });
3425 - 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;
3426 4262 });
3427 4263
3428 4264
3429 -mainwp_notice_dismiss = function (notice_id, time_set) {
3430 - var data = {
3431 - action: 'mainwp_notice_status_update'
3432 - };
3433 - data['notice_id'] = notice_id;
3434 - if (typeof time_set !== "undefined") {
3435 - data['time_set'] = time_set ? 1 : 0;
3436 - }
3437 - jQuery.post(ajaxurl, mainwp_secure_data(data), function () {
3438 - console.log('dismissed');
3439 - });
3440 - 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;
3441 4276 }
3442 4277
3443 4278
3444 4279 jQuery(document).on('click', '.mainwp-activate-notice-dismiss', function () {
3445 - jQuery(this).closest('tr').fadeOut("slow");
3446 - var data = mainwp_secure_data({
3447 - action: 'mainwp_dismiss_activate_notice',
3448 - slug: jQuery(this).closest('tr').attr('slug')
3449 - });
3450 - jQuery.post(ajaxurl, data, function () {
3451 - });
3452 - 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;
3453 4288 });
3454 4289
3455 4290 jQuery(document).on('click', '.mainwp-install-check-dismiss', function () {
3456 - var notice_id = jQuery(this).attr('notice-id');
3457 - jQuery(this).closest('.ui.message').fadeOut("slow");
3458 - var data = {
3459 - action: 'mainwp_notice_status_update'
3460 - };
3461 - data['notice_id'] = notice_id;
3462 - jQuery.post(ajaxurl, mainwp_secure_data(data), function () { });
3463 - 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;
3464 4299 });
3465 4300
3466 -jQuery(document).on('click', '.mainwp-action-dismiss', function () {
3467 - var action_id = jQuery(this).attr('action-id');
3468 - jQuery(this).closest('tr').fadeOut("slow");
3469 - var data = {
3470 - action: 'mainwp_site_actions_dismiss'
3471 - };
3472 - data['action_id'] = action_id;
3473 - jQuery.post(ajaxurl, mainwp_secure_data(data), function () {
3474 -
3475 - });
3476 - 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;
3477 4306 });
3478 4307
3479 -jQuery(document).on('click', '#mainwp-delete-all-nonmainwp-actions-button', function () {
3480 - mainwp_confirm('Are you sure you want to delete all Non-MainWP changes? This action can not be undone!', function () {
3481 - mainwp_delete_nonmainwp_data_start();
3482 - });
3483 - return false;
3484 -});
3485 -
3486 -mainwp_managesites_update_childsite_value = function (siteId, uniqueId) {
3487 - var data = mainwp_secure_data({
3488 - action: 'mainwp_updatechildsite_value',
3489 - site_id: siteId,
3490 - unique_id: uniqueId
3491 - });
3492 - jQuery.post(ajaxurl, data, function () {
3493 - });
3494 - return false;
4308 +let mainwp_managesites_update_childsite_value = function (siteId, uniqueId) {
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;
3495 4317 };
3496 4318
3497 4319 jQuery(document).on('keyup', '#managegroups-filter', function () {
3498 - var filter = jQuery(this).val();
3499 - var groupItems = jQuery(this).parent().parent().find('li.managegroups-listitem');
3500 - for (var i = 0; i < groupItems.length; i++) {
3501 - var currentElement = jQuery(groupItems[i]);
3502 - if (currentElement.hasClass('managegroups-group-add'))
3503 - continue;
3504 - var value = currentElement.find('span.text').text();
3505 - if (value.indexOf(filter) > -1) {
3506 - currentElement.show();
3507 - } else {
3508 - currentElement.hide();
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 + }
3509 4333 }
3510 - }
3511 4334 });
3512 4335
3513 4336 // for normal checkboxes
3514 4337 jQuery(document).on('change', '#cb-select-all-top, #cb-select-all-bottom', function () {
3515 - var $this = jQuery(this),
3516 - $table = $this.closest('table'),
3517 - controlChecked = $this.prop('checked');
4338 + let $this = jQuery(this), $table, controlChecked = $this.prop('checked');
3518 4339
3519 - if ($table.length == 0)
3520 - return false;
4340 + $table = $this.closest('.dt-scroll').find('.dt-scroll-body table'); // for dt with scroll enabled.
3521 4341
3522 - $table.children('tbody').filter(':visible')
3523 - .children().children('.check-column').find(':checkbox')
3524 - .prop('checked', function () {
3525 - if (jQuery(this).is(':hidden,:disabled')) {
4342 + // if no scrollable table.
4343 + if ($table.length == 0) {
4344 + $table = $this.closest('table.table.dataTable');
4345 + }
4346 +
4347 + if ($table.length == 0)
3526 4348 return false;
3527 - }
3528 - if (controlChecked) {
3529 - return true;
3530 - }
3531 - return false;
4349 +
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'); });
3532 4408 });
3533 4409
3534 - $table.children('thead, tfoot').filter(':visible')
3535 - .children().children('.check-column').find(':checkbox')
3536 - .prop('checked', function () {
3537 - if (controlChecked) {
3538 - return true;
3539 - }
3540 - 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'); });
3541 4413 });
3542 -});
3543 4414
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 + });
3544 4423
3545 -jQuery(function ($) {
3546 - // Trigger the bulk actions
3547 - $('#mainwp_non_mainwp_actions_action_btn').on('click', function () {
3548 - var bulk_act = jQuery('#non_mainwp_actions_bulk_action').dropdown("get value");
3549 - var confirmMsg = '';
3550 - switch (bulk_act) {
3551 - case 'delete':
3552 - confirmMsg = __("You are about to delete the selected changes?");
3553 - break;
3554 - case 'dismiss':
3555 - confirmMsg = __("You are about to dismiss the selected changes?");
3556 - break;
3557 - }
3558 - if (confirmMsg == '') {
3559 - return false;
3560 - }
3561 - mainwp_confirm(confirmMsg, function () { mainwp_non_mainwp_actions_table_bulk_action(bulk_act); });
3562 - return false; // return those case
3563 - });
4424 + $(document).on('click', '.insights-actions-row-dismiss', function () {
4425 + return mainwp_insights_row_actions_dismiss(this);
4426 + });
3564 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;
3565 4431
3566 - $(document).on('click', '.non-mainwp-action-row-dismiss', function () {
3567 - var row = $(this).closest('tr');
3568 - var confirmMsg = __("You are about to dismiss the selected changes?");
3569 - mainwp_confirm(confirmMsg, function () {
3570 - row.html('<td></td><td colspan="999"><i class="notched circle loading icon"></i> Please wait...</td>');
3571 - var data = mainwp_secure_data({
3572 - action: 'mainwp_non_mainwp_changes_dismiss_actions',
3573 - act_id: $(row).attr('action-id')
3574 - });
3575 - $.post(ajaxurl, data, function (response) {
3576 - if (response) {
3577 - if (response['error']) {
3578 - row.html('<td></td><td colspan="999"><i class="times red icon"></i> ' + response['error'] + '</td>');
3579 - } else if (response['success'] == 'yes') {
3580 - row.html('<td></td><td colspan="999"><i class="green check icon"></i> Non-MainWP Change has been dismissed.</td>');
3581 - setTimeout(function () {
3582 - jQuery(row).fadeOut("slow");
3583 - }, 2000);
3584 - } else {
3585 - row.html('<td></td><td colspan="999"><i class="times red icon"></i> Non-MainWP Change could not be dismissed.</td>');
3586 - }
4432 + if (checkedCount > 0) {
4433 + jQuery('#mainwp_sites_changes_bulk_dismiss_selected_btn').removeClass('disabled');
3587 4434 } else {
3588 - row.html('<td></td><td colspan="999"><i class="times red icon"></i> Non-MainWP Change could not be dismissed.</td>');
4435 + jQuery('#mainwp_sites_changes_bulk_dismiss_selected_btn').addClass('disabled');
3589 4436 }
3590 - }, 'json');
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 + }
4443 + }
4444 +
4445 + jQuery(document).on('change', '#mainwp-module-log-records-body-table input[type="checkbox"]', function () {
4446 + mainwp_sites_changes_update_dismiss_button_state();
3591 4447 });
3592 4448
4449 + jQuery(document).on('change', '#cb-select-all-top, #cb-select-all-bottom', function () {
4450 + mainwp_sites_changes_update_dismiss_button_state();
4451 + });
4452 +})
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?");
4457 +
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 + };
4467 +
4468 + const updateDismissButtonState = () => {
4469 + if (typeof mainwp_sites_changes_update_dismiss_button_state !== 'undefined') {
4470 + mainwp_sites_changes_update_dismiss_button_state();
4471 + }
4472 + };
4473 +
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);
3593 4502 return false;
3594 - });
3595 -})
4503 +}
3596 4504
3597 4505
3598 4506 // Manage Bulk Actions
3599 -mainwp_non_mainwp_actions_table_bulk_action = function (act) {
3600 - bulkInstallTotal = 0;
3601 - bulkInstallCurrentThreads = 0;
3602 - bulkInstallDone = 0;
3603 - var selector = '';
3604 - switch (act) {
3605 - case 'dismiss':
3606 - selector += '#mainwp-manage-non-mainwp-actions-table tbody tr';
3607 - jQuery(selector).addClass('queue');
3608 - mainwp_non_mainwp_actions_dismiss_start_next(selector, true);
3609 - break;
3610 - }
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 + }
3611 4532 }
3612 4533
3613 -mainwp_non_mainwp_actions_dismiss_start_next = function (selector) {
3614 - if (bulkInstallTotal == 0) {
3615 - bulkInstallTotal = jQuery('#mainwp-manage-non-mainwp-actions-table tbody').find('input[type="checkbox"]:checked').length;
3616 - }
3617 - while ((objProcess = jQuery(selector + '.queue:first')) && (objProcess.length > 0) && (bulkInstallCurrentThreads < bulkInstallMaxThreads)) {
3618 - objProcess.removeClass('queue');
3619 - if (objProcess.closest('tr').find('input[type="checkbox"]:checked').length == 0) {
3620 - 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);
3621 4541 }
3622 - mainwp_non_mainwp_actions_dismiss_specific(objProcess, selector, true);
3623 - }
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 + }
3624 4553 }
3625 4554
3626 -mainwp_non_mainwp_actions_dismiss_specific = function (pObj, selector, pBulk) {
3627 - var row = pObj.closest('tr');
3628 - var act_id = jQuery(row).attr('action-id');
3629 - var bulk = pBulk ? true : false;
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');
3630 4558
3631 - if (bulk) {
3632 4559 bulkInstallCurrentThreads++;
3633 - }
3634 4560
3635 - var data = mainwp_secure_data({
3636 - action: 'mainwp_non_mainwp_changes_dismiss_actions',
3637 - act_id: act_id,
3638 - });
4561 + let data = mainwp_secure_data({
4562 + action: 'mainwp_insight_events_dismiss_actions',
4563 + log_id: act_id
4564 + });
3639 4565
3640 - 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>');
3641 4567
3642 - jQuery.post(ajaxurl, data, function (response) {
3643 - pObj.removeClass('queue');
3644 - if (response) {
3645 - if (response['error']) {
3646 - row.html('<td></td><td colspan="999"><i class="times red icon"></i> ' + response['error'] + '</td>');
3647 - } else if (response['success'] == 'yes') {
3648 - row.html('<td></td><td colspan="999"><i class="green check icon"></i> Non-MainWP Change has been dismissed.</td>');
3649 - setTimeout(function () {
3650 - jQuery(row).fadeOut("slow");
3651 - }, 2000);
3652 - } else {
3653 - row.html('<td></td><td colspan="999"><i class="times red icon"></i> Failed. Please try again.</td>');
3654 - }
3655 - } else {
3656 - row.html('<td></td><td colspan="999"><i class="times red icon"></i> Failed. Please try again.</td>');
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 + }
4584 +
4585 + bulkInstallCurrentThreads--;
4586 + bulkInstallDone++;
4587 + mainwp_sites_changes_actions_dismiss_start_next(selector);
4588 + }, 'json');
4589 + return false;
4590 +}
4591 +
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 +
4615 +}
4616 +
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 + }
3657 4625 }
4626 +}
3658 4627
3659 - if (bulk) {
3660 - bulkInstallCurrentThreads--;
3661 - bulkInstallDone++;
3662 - mainwp_non_mainwp_actions_dismiss_start_next(selector);
3663 - if (bulkInstallTotal == bulkInstallDone) {
3664 - setTimeout(function () {
3665 - window.location.reload(true);
3666 - }, 3000);
3667 - }
4628 +globalThis.mainwp_datatable_fix_to_update_rows_state = function (tblSelect) {
4629 + if (jQuery(tblSelect).length) {
4630 + let $table = jQuery(tblSelect);
4631 +
4632 + let dtApi = jQuery($table).dataTable().api(); // NOTE: not use DataTable().
4633 +
4634 + mainwp_datatable_fix_to_update_selected_rows_status(dtApi, 'deselected'); // clear saved state.
4635 +
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 + });
4643 +
4644 + mainwp_datatable_fix_to_update_selected_rows_status(dtApi, 'selected'); // to update selected state.
3668 4645 }
3669 -
3670 - }, 'json');
3671 - return false;
3672 4646 }
3673 4647
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);
4650 +};
3674 4651
3675 4652 // fix menu overflow with scroll tables.
3676 -mainwp_datatable_fix_menu_overflow = function (pTableSelector, pTop, pRight, pLeft) {
3677 - var fix_overflow = jQuery('.mainwp-content-wrap').attr('menu-overflow');
3678 - jQuery(document).on('click', 'table td.check-column.dtr-control', function () {
3679 - if (jQuery(this).parent().hasClass('parent')) {
3680 - var chilRow = jQuery(this).parent().next();
3681 - jQuery(chilRow).find('.ui.dropdown').dropdown();
3682 - 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');
3683 4656 }
3684 - });
3685 - var tblSelect = pTableSelector !== '' && pTableSelector !== undefined && pTableSelector !== false ? 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';
3686 4668
3687 - 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 + });
3688 4676
3689 - // Fix the overflow prbolem for the actions menu element (right pointing menu).
3690 - jQuery(tblSelect + ' tr td .ui.right.pointing.dropdown.button').on('click', function () {
3691 - jQuery(this).closest('.dataTables_scrollBody').css('position', '');
3692 - jQuery(this).closest('.dataTables_scroll').css('position', 'relative');
3693 - jQuery(this).css('position', 'static');
3694 - var fix_overflow = jQuery('.mainwp-content-wrap').attr('menu-overflow');
3695 - var position = jQuery(this).position();
3696 - var top = position.top;
3697 - var right = 48;
3698 - if (fix_overflow > 1) {
3699 - position = jQuery(this).closest('td').position();
3700 - 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 + }
3701 4689 }
3702 - if (pTop !== undefined) {
3703 - top = top + pTop;
3704 - }
3705 - if (pRight !== undefined) {
3706 - right = right + pRight;
3707 - }
3708 - console.log('right');
3709 - console.log('top: ' + top + ' right: ' + right);
3710 - //return false;
3711 - jQuery(this).find('.menu').css('min-width', '170px');
3712 - jQuery(this).find('.menu').css('top', top);
3713 - jQuery(this).find('.menu').css('right', right + ' !important;');
3714 - jQuery(this).find('.menu')[0].style.setProperty('right', right + 'px', 'important'); // to fix important in jquery.
3715 - });
3716 4690
3717 - // Fix the overflow prbolem for the actions menu element (left pointing menu).
3718 - jQuery(tblSelect + ' tr td .ui.left.pointing.dropdown.button').on('click', function () {
3719 - jQuery(this).closest('.dataTables_scrollBody').css('position', '');
3720 - jQuery(this).closest('.dataTables_scroll').css('position', 'relative');
3721 - jQuery(this).css('position', 'static');
3722 - var position = jQuery(this).position();
3723 4691
3724 - var top = position.top;
3725 - var 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 + }
3726 4705
3727 - if (fix_overflow > 1) {
3728 - position = jQuery(this).closest('td').position();
3729 - var scroll_left = jQuery(this).closest('.dataTables_scrollBody').scrollLeft();
3730 - top = position.top + 85;
3731 - left = position.left - scroll_left - 145;
3732 - }
4706 + if (pTop !== undefined) {
4707 + top = top + pTop;
4708 + }
4709 + if (pRight !== undefined) {
4710 + right = right + pRight;
4711 + }
3733 4712
3734 - if (pTop !== undefined) {
3735 - top = top + pTop;
3736 - }
3737 -
3738 - if(undefined !== pLeft){
3739 - left -= pLeft; // custom left.
3740 - }
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 + });
3741 4717
3742 - console.log('left');
3743 - 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();
3744 4724
3745 - jQuery(this).find('.menu').css('min-width', '150px');
3746 - jQuery(this).removeClass('left');
3747 - jQuery(this).addClass('right');
3748 - //return false;
3749 - jQuery(this).find('.menu').css('top', top);
3750 - jQuery(this).find('.menu').css('left', left);
3751 - });
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();
3752 4751 }
3753 4752
3754 -mainwp_datatable_fix_child_menu_overflow = function (chilRow, fix_overflow) {
3755 - // Fix the overflow prbolem for the actions child menu element (pointing menu).
3756 - jQuery(chilRow).find('.ui.pointing.dropdown.button').on('click', function () {
3757 4753
3758 - var position = jQuery(this).position();
3759 - var left = position.left + 30;
3760 - var top = position.top;
4754 +let mainwp_datatable_fix_child_menu_overflow = function (chilRow, fix_overflow) {
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 () {
3761 4759
3762 - if (fix_overflow > 1) {
3763 - position = jQuery(this).closest('td.child').position();
3764 - top = position.top + jQuery(this).closest('td.child').height() + 85;
3765 - }
4760 + let position = jQuery(this).position();
4761 + let left = position.left + 30;
4762 + let top = position.top;
3766 4763
3767 - jQuery(this).closest('.dataTables_scrollBody').css('position', '');
3768 - jQuery(this).closest('.dataTables_scroll').css('position', 'relative');
3769 - jQuery(this).css('position', 'static');
3770 - jQuery(this).find('.menu').css('top', top);
3771 - jQuery(this).find('.menu').css('left', left);
3772 - jQuery(this).find('.menu').css('min-width', '170px');
3773 - console.log('top:' + top);
3774 - });
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 + }
4768 +
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 + });
3775 4776 }
3776 4777
3777 4778
3778 -mainwp_responsive_fix_remove_child_row = function (el) {
3779 - if (jQuery(el).hasClass('dt-hasChild')) { // to fix.
3780 - jQuery(el).next().remove();
3781 - }
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 + }
3782 4783 }
3783 4784
3784 4785 /* eslint-disable complexity */
3785 -function mainwp_according_table_sorting(pObj) {
3786 - var table, th, rows, switching, i, x, y, xVal, yVal, campare = false, shouldSwitch = false, dir, switchcount = 0, n, skip = 1;
3787 - table = jQuery(pObj).closest('table')[0];
3788 - var subline_skip = 2;
3789 - if ('mainwp-wordpress-updates-table' == jQuery(table).attr('id')) {
3790 - subline_skip = 1; // for rows without subline.
3791 - skip = 0;
3792 - }
4786 +function mainwp_according_table_sorting(pObj) { // NOSONAR - complex.
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 + }
3793 4794
3794 - // get TH element
3795 - if (jQuery(pObj)[0].tagName == 'TH') {
3796 - th = jQuery(pObj)[0];
3797 - } else {
3798 - th = jQuery(pObj).closest('th')[0];
3799 - }
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 + }
3800 4801
3801 - n = th.cellIndex;
3802 - switching = true;
4802 + n = th.cellIndex;
4803 + switching = true;
3803 4804
3804 - // check header and footer of according table
3805 - if (jQuery(table).children('thead,tfoot').length > 0)
3806 - 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
3807 4808
3808 - dir = "asc";
3809 - /* loop until switching has been done: */
3810 - while (switching) {
3811 - switching = false;
3812 - rows = table.rows;
3813 - /* Loop through all table rows */
3814 - for (i = 1; i < (rows.length - skip); i += subline_skip) { // skip content according rows, sort by title rows only
3815 - shouldSwitch = false;
3816 - /* Get the two elements you want to compare,
3817 - one from current row and one from the next-next: */
3818 - x = rows[i].getElementsByTagName("TD")[n];
3819 - 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];
3820 4821
3821 - // if sort value attribute existed then sorting on that else sorting on cell value
3822 - if (x.hasAttribute('sort-value')) {
3823 - xVal = parseInt(x.getAttribute('sort-value'));
3824 - yVal = parseInt(y.getAttribute('sort-value'));
3825 - campare = (xVal == yVal) ? 0 : (xVal > yVal ? -1 : 1);
3826 - } else {
3827 - // to prevent text() clear text content
3828 - xVal = '<p>' + x.innerHTML + '</p>';
3829 - yVal = '<p>' + y.innerHTML + '</p>';
3830 - xVal = jQuery(xVal).text().trim().toLowerCase();
3831 - yVal = jQuery(yVal).text().trim().toLowerCase();
3832 - campare = yVal.localeCompare(xVal);
3833 - }
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 + }
3834 4836
3835 - /* Check if the two rows should switch place */
3836 - if (dir == "asc") {
3837 - if (campare < 0) { //xVal > yVal
3838 - shouldSwitch = true;
3839 - // break the loop:
3840 - 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 + }
3841 4851 }
3842 - } else if (dir == "desc") {
3843 - if (campare > 0) { //xVal < yVal
3844 - // break the loop:
3845 - shouldSwitch = true;
3846 - 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;
3847 4867 }
3848 - }
3849 4868 }
3850 - if (shouldSwitch) {
3851 - if (2 == subline_skip) {
3852 - rows[i].parentNode.insertBefore(rows[i + 2], rows[i]);
3853 - rows[i + 1].parentNode.insertBefore(rows[i + 3], rows[i + 1]);
3854 - } else {
3855 - rows[i].parentNode.insertBefore(rows[i + 1], rows[i]); // switch 2 rows.
3856 - }
3857 - switching = true;
3858 - // increase this count by 1, that is ok
3859 - switchcount++;
3860 - } else {
3861 - /* If no switching has been done AND the direction is "asc",
3862 - set the direction to "desc" and run the while loop again. */
3863 - if (switchcount == 0 && dir == "asc") {
3864 - dir = "desc";
3865 - switching = true;
3866 - }
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 + }
3867 4877 }
3868 - }
3869 4878
3870 - // no row sorting so change direction for arrows switch
3871 - if (switchcount == 0) {
3872 - if (jQuery(pObj).hasClass('ascending')) {
3873 - dir = "desc";
4879 + // add/remove class for arrows displaying
4880 + if (dir == "asc") {
4881 + jQuery(pObj).addClass('ascending');
4882 + jQuery(pObj).removeClass('descending');
3874 4883 } else {
3875 - dir = "asc";
4884 + jQuery(pObj).removeClass('ascending');
4885 + jQuery(pObj).addClass('descending');
3876 4886 }
3877 - }
3878 -
3879 - // add/remove class for arrows displaying
3880 - if (dir == "asc") {
3881 - jQuery(pObj).addClass('ascending');
3882 - jQuery(pObj).removeClass('descending');
3883 - } else {
3884 - jQuery(pObj).removeClass('ascending');
3885 - jQuery(pObj).addClass('descending');
3886 - }
3887 4887 }
3888 4888 /* eslint-enable complexity */
3889 4889
3890 -jQuery(document).ready(function () {
3891 - jQuery('.handle-accordion-sorting').on('click', function () {
3892 - mainwp_according_table_sorting(this);
3893 - return false;
3894 - });
4890 +jQuery(function () {
4891 + jQuery('.handle-accordion-sorting').on('click', function () {
4892 + mainwp_according_table_sorting(this);
4893 + return false;
4894 + });
3895 4895 });
3896 4896
3897 4897 // Force Dashboard to reestablish connection by destroying sessions - Part 1
3898 -mainwp_force_destroy_sessions = function () {
3899 - var confirmMsg = __('Are you sure you want to force your MainWP Dashboard to reconnect with your child sites?');
3900 - mainwp_confirm(confirmMsg, function () {
3901 - mainwp_force_destroy_sessions_websites = jQuery('.dashboard_wp_id').map(function (indx, el) {
3902 - return jQuery(el).val();
4898 +let mainwp_force_destroy_sessions = function () {
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);
3903 4907 });
3904 - mainwpPopup('#mainwp-sync-sites-modal').setTitle(__('Re-establish Connection')); // popup displayed.
3905 - mainwpPopup('#mainwp-sync-sites-modal').init({ progressMax: mainwp_force_destroy_sessions_websites.length });
3906 - mainwp_force_destroy_sessions_part_2(0);
3907 - });
3908 4908 };
3909 4909
3910 -mainwp_force_destroy_sessions_part_2 = function (id) {
3911 - if (id >= mainwp_force_destroy_sessions_websites.length) {
3912 - mainwp_force_destroy_sessions_websites = [];
3913 - if (mainwp_force_destroy_sessions_successed == mainwp_force_destroy_sessions_websites.length) {
3914 - setTimeout(function () {
4910 +let mainwp_force_destroy_sessions_part_2 = function (id) {
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 + }
3915 4918 mainwpPopup('#mainwp-sync-sites-modal').close(true);
3916 - }, 3000);
4919 + return;
3917 4920 }
3918 - mainwpPopup('#mainwp-sync-sites-modal').close(true);
3919 - return;
3920 - }
3921 4921
3922 - var website_id = mainwp_force_destroy_sessions_websites[id];
3923 - 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>');
3924 4924
3925 - jQuery.post(ajaxurl, { 'action': 'mainwp_force_destroy_sessions', 'website_id': website_id, 'security': security_nonces['mainwp_force_destroy_sessions'] }, function (response) {
3926 - var counter = id + 1;
3927 - 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);
3928 4928
3929 - mainwpPopup('#mainwp-sync-sites-modal').setProgressSite(counter);
4929 + mainwpPopup('#mainwp-sync-sites-modal').setProgressSite(counter);
3930 4930
3931 - if ('error' in response) {
3932 - dashboard_update_site_status(website_id, '<i class="exclamation red icon"></i>');
3933 - } else if ('success' in response) {
3934 - mainwp_force_destroy_sessions_successed += 1;
3935 - dashboard_update_site_status(website_id, '<i class="check green icon"></i>', true);
3936 - } else {
3937 - dashboard_update_site_status(website_id, '<span data-inverted="" data-position="left center" data-tooltip="' + __('Process timed out. Please try again.', 'mainwp') + '">');
3938 - }
3939 - }, 'json').fail(function () {
3940 - var counter = id + 1;
3941 - mainwp_force_destroy_sessions_part_2(counter);
3942 - 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);
3943 4943
3944 - dashboard_update_site_status(website_id, '<i class="exclamation red icon"></i>');
3945 - });
4944 + dashboard_update_site_status(website_id, '<i class="exclamation red icon"></i>');
4945 + });
3946 4946
3947 4947 };
3948 4948
3949 -var mainwp_force_destroy_sessions_successed = 0;
3950 -var mainwp_force_destroy_sessions_websites = [];
4949 +let mainwp_force_destroy_sessions_successed = 0;
4950 +let mainwp_force_destroy_sessions_websites = [];
3951 4951
3952 4952
3953 4953 jQuery(document).on('change', '#mainwp_archiveFormat', function () {
3954 - var zipMethod = jQuery(this).val();
3955 - zipMethod = zipMethod.replace(/\./g, '\\.');
3956 - jQuery('span.archive_info').hide();
3957 - 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();
3958 4958
3959 - jQuery('tr.archive_method').hide();
3960 - jQuery('tr.archive_' + zipMethod).show();
4959 + jQuery('tr.archive_method').hide();
4960 + jQuery('tr.archive_' + zipMethod).show();
3961 4961
3962 - // compare new layout
3963 - jQuery('div.archive_method').hide();
3964 - jQuery('div.archive_' + zipMethod).show();
4962 + // compare new layout
4963 + jQuery('div.archive_method').hide();
4964 + jQuery('div.archive_' + zipMethod).show();
3965 4965 });
3966 4966
4967 +let mainwp_import_demo_data_action = function (obj) {
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 + });
3967 4975
3968 -// MainWP Tools
3969 -jQuery(function () {
3970 - jQuery(document).on('click', '#force-destroy-sessions-button', function () {
3971 - mainwp_force_destroy_sessions();
3972 - });
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 + }
3973 4984
3974 - jQuery(document).on('click', '.mainwp-import-demo-data-button', function () {
3975 - var confirmation = "Are you sure you want to import demo content into your MainWP Dashboard?";
3976 - var msg_import = (jQuery(this).attr('page-import') == 'qsw-import') ? '&message=qsw-import' : '';
3977 - mainwp_confirm(confirmation, function () {
3978 - feedback('mainwp-message-zone', '<i class="notched circle loading icon"></i> ' + __('Importing. Please wait...', 'mainwp'), '');
3979 - var data = mainwp_secure_data({
3980 - action: 'mainwp_import_demo_data',
3981 - });
3982 -
3983 - jQuery.post(ajaxurl, data, function (response) {
3984 - var error = false;
3985 - if (response.count != undefined) {
3986 - feedback('mainwp-message-zone', __('The demo content has been imported into your MainWP Dashboard.', 'mainwp'), 'green');
3987 - } else {
3988 - error = true;
3989 - feedback('mainwp-message-zone', __('Undefined error. Please try again.', 'mainwp'), 'green');
3990 - }
3991 - if (error == false) {
3992 - setTimeout(function () {
3993 - window.location = 'admin.php?page=mainwp_tab' + msg_import;
3994 - }, 3000);
3995 - }
3996 - }, 'json');
4985 + if (!error) {
4986 + setTimeout(function () {
4987 + mainwp_forceReload('admin.php?page=mainwp_tab' + msg_import);
4988 + }, 3000);
4989 + }
4990 + }, 'json');
3997 4991 });
3998 - return false;
3999 - });
4992 +}
4000 4993
4001 - jQuery(document).on('click', '.mainwp-remove-demo-data-button', function () {
4002 -
4003 - var confirmation = "Are you sure you want to delete demo content from your MainWP Dashboard?";
4994 +let mainwp_remove_demo_data_action = function () {
4995 + let confirmation = "Are you sure you want to delete demo content from your MainWP Dashboard?";
4004 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 + }
4005 5009
4006 - feedback('mainwp-message-zone', '<i class="notched circle loading icon"></i> ' + __('Deleting. Please wait...', 'mainwp'), '');
5010 + if (!error) {
5011 + setTimeout(function () {
5012 + mainwp_forceReload('admin.php?page=mainwp-setup');
5013 + }, 3000);
5014 + }
4007 5015
4008 - var data = mainwp_secure_data({
4009 - action: 'mainwp_delete_demo_data',
4010 - });
5016 + }, 'json');
5017 + });
5018 +}
4011 5019
4012 - jQuery.post(ajaxurl, data, function (response) {
5020 +// MainWP Tools
5021 +jQuery(function () {
5022 + jQuery(document).on('click', '#force-destroy-sessions-button', function () {
5023 + mainwp_force_destroy_sessions();
5024 + });
4013 5025
4014 - var error = false;
5026 + jQuery(document).on('click', '.mainwp-import-demo-data-button', function (event) {
5027 + mainwp_import_demo_data_action(this);
5028 + event.preventDefault();
5029 + });
4015 5030
4016 - if (response.success != undefined) {
4017 - feedback('mainwp-message-zone', __('The demo content has been deleted from your MainWP Dashboard.', 'mainwp'), 'green');
4018 - } else {
4019 - error = true;
4020 - feedback('mainwp-message-zone', __('Undefined error. Please try again.', 'mainwp'), 'green');
4021 - }
4022 -
4023 - if (error == false) {
4024 - setTimeout(function () {
4025 - window.location = 'admin.php?page=mainwp-setup';
4026 - }, 3000);
4027 - }
4028 -
4029 - }, 'json');
5031 + jQuery(document).on('click', '.mainwp-remove-demo-data-button', function () {
5032 + mainwp_remove_demo_data_action();
5033 + return false; //required this return.
4030 5034 });
4031 - return false;
4032 - });
4033 -
4034 -
4035 5035 });
4036 5036
4037 5037
4038 -mainwp_tool_renew_connections_show = function () {
4039 - jQuery('#mainwp-tool-renew-connect-modal').modal({
4040 - allowMultiple: true,
4041 - closable: false,
4042 - onHide: function () {
4043 - location.href = 'admin.php?page=MainWPTools';
4044 - },
4045 - onShow: function () {
4046 - if (jQuery('#mainwp-tool-renew-connect-modal .mainwp_selected_sites_item.item.warning').length == 0) {
4047 - jQuery('#mainwp-tool-renew-connect-modal .mainwp-ss-select-disconnected').hide();
4048 - jQuery('#mainwp-tool-renew-connect-modal .mainwp-ss-deselect-disconnected').hide();
4049 - }
4050 - }
4051 - }).modal('show');
5038 +let mainwp_tool_renew_connections_show = function () {
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');
4052 5052 };
4053 5053
4054 -mainwp_tool_prepare_renew_connections = function (objBtn) {
5054 +let mainwp_tool_prepare_renew_connections = function (objBtn) {
4055 5055
4056 - var errors = [];
4057 - var selected_sites = [];
5056 + let errors = [];
5057 + let selected_sites = [];
5058 + mainwp_set_message_zone('#mainwp-message-zone-modal');
4058 5059
4059 - jQuery('#mainwp-message-zone-modal').removeClass('yellow ').hide();
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 + }
4060 5066
4061 - jQuery("input[name='selected_sites[]']:checked").each(function () {
4062 - selected_sites.push(jQuery(this).val());
4063 - });
4064 - if (selected_sites.length == 0) {
4065 - errors.push(__('Please select at least one website to start.'));
4066 - }
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 + }
4067 5073
4068 - if (errors.length > 0) {
4069 - jQuery('#mainwp-message-zone-modal').html(errors.join('<br />'));
4070 - jQuery('#mainwp-message-zone-modal').addClass('yellow ').show();
4071 - return;
4072 - } else {
4073 - jQuery('#mainwp-message-zone-modal').html("");
4074 - jQuery('#mainwp-message-zone-modal').removeClass('yellow ').hide();
4075 - }
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?");
4076 5075
4077 - var 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?");
5076 + mainwp_confirm(confirmation, function () {
5077 + jQuery(objBtn).attr('disabled', true);
4078 5078
4079 - mainwp_confirm(confirmation, function () {
4080 - jQuery(objBtn).attr('disabled', true);
5079 + jQuery('#mainwp-tool-renew-connect-modal .mainwp-select-sites-wrapper').hide();
4081 5080
4082 - jQuery('#mainwp-tool-renew-connect-modal .mainwp-select-sites-wrapper').hide();
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();
4083 5084
4084 - var statusEl = jQuery('#mainwp-message-zone-modal');
4085 - statusEl.html('<i class="notched circle loading icon"></i> ' + __('Please wait...'));
4086 - statusEl.show();
5085 + let data = mainwp_secure_data({
5086 + action: 'mainwp_prepare_renew_connections',
5087 + 'sites[]': selected_sites,
5088 + });
4087 5089
4088 - var data = mainwp_secure_data({
4089 - action: 'mainwp_prepare_renew_connections',
4090 - 'sites[]': selected_sites,
4091 - });
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 + }
4092 5109
4093 - jQuery.post(ajaxurl, data, function (response) {
4094 - var undefError = false;
4095 - if (response) {
4096 - if (response.result != '') {
4097 - jQuery('#mainwp-tool-renew-connect-modal').find('#mainwp-renew-connections-list').html(response.result);
4098 - bulkInstallTotal = jQuery('#mainwp-renew-connections-list .item').length;
4099 - jQuery('#mainwp-tool-renew-connect-modal .mainwp-modal-progress').show();
4100 - jQuery('#mainwp-tool-renew-connect-modal .mainwp-modal-progress').progress({ value: 0, total: bulkInstallTotal });
4101 - mainwp_tool_renew_connections_start_next();
4102 - statusEl.hide();
4103 - } else if (response.error) {
4104 - statusEl.addClass('red');
4105 - statusEl.html(response.error).fadeIn();
4106 - } else {
4107 - undefError = true;
4108 - }
4109 - } else {
4110 - undefError = true;
4111 - }
4112 -
4113 - if (undefError) {
4114 - statusEl.addClass('red');
4115 - statusEl.html(__('Undefined error occurred. Please try again.')).fadeIn();
4116 - }
4117 - }, 'json');
4118 - }, 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);
4119 5116 }
4120 5117
4121 -connection_renew_status = function (siteId, newStatus) {
4122 - jQuery('#mainwp-renew-connections-list .renew-site-status[siteid="' + siteId + '"]').html(newStatus);
5118 +let connection_renew_status = function (siteId, newStatus) {
5119 + jQuery('#mainwp-renew-connections-list .renew-site-status[siteid="' + siteId + '"]').html(newStatus);
4123 5120 };
4124 5121
4125 -mainwp_tool_renew_connections_start_next = function () {
4126 - while ((siteToReNew = jQuery('#mainwp-renew-connections-list .item[status="queue"]:first')) && (siteToReNew.length > 0) && (bulkInstallCurrentThreads < bulkInstallMaxThreads)) {
4127 - mainwp_tool_renew_connections_start_specific(siteToReNew);
4128 - }
5122 +let mainwp_tool_renew_connections_start_next = function () {
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 + }
4129 5126 }
4130 5127
4131 -mainwp_tool_renew_connections_start_specific = function (siteItem) {
5128 +let mainwp_tool_renew_connections_start_specific = function (siteItem) {
4132 5129
4133 - bulkInstallCurrentThreads++;
5130 + bulkInstallCurrentThreads++;
4134 5131
4135 - siteItem.attr('status', 'progress');
4136 - var siteId = siteItem.find('.renew-site-status').attr('siteid');
5132 + siteItem.attr('status', 'progress');
5133 + let siteId = siteItem.find('.renew-site-status').attr('siteid');
4137 5134
4138 - var data = mainwp_secure_data({
4139 - action: 'mainwp_renew_connections',
4140 - siteid: siteId
4141 - });
5135 + let data = mainwp_secure_data({
5136 + action: 'mainwp_renew_connections',
5137 + siteid: siteId
5138 + });
4142 5139
4143 - connection_renew_status(siteId, '<span data-inverted="" data-position="left center" data-tooltip="' + __('Processing...', 'mainwp') + '"><i class="sync alternate loading icon"></i></span>');
4144 - jQuery.post(ajaxurl, data, function (response) {
4145 - if (response.error) {
4146 - connection_renew_status(siteId, '<span data-inverted="" data-position="left center" data-tooltip="' + response.error + '"><i class="times red icon"></i></span>');
4147 - } else if (response.result == 'success') {
4148 - 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>', true);
4149 - } else {
4150 - 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>');
4151 5148
4152 - }
4153 - bulkInstallCurrentThreads--;
4154 - bulkInstallDone++;
4155 - jQuery('#mainwp-tool-renew-connect-modal .mainwp-modal-progress').progress('set progress', bulkInstallDone);
4156 - jQuery('#mainwp-tool-renew-connect-modal .mainwp-modal-progress').find('.label').html(bulkInstallDone + '/' + bulkInstallTotal + ' ' + __('Processed'));
4157 - mainwp_tool_renew_connections_start_next();
4158 - }, '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');
4159 5156 }
4160 5157
4161 5158
4162 5159 jQuery(function () {
4163 - if (jQuery('body.mainwp-ui').length > 0) {
4164 - jQuery('.mainwp-ui-page .ui.dropdown:not(.not-auto-init)').dropdown();
4165 - jQuery('.mainwp-ui-page .ui.checkbox:not(.not-auto-init)').checkbox();
4166 - jQuery('.mainwp-ui-page .ui.dropdown').filter('[init-value]').each(function () {
4167 - var values = jQuery(this).attr('init-value').split(',');
4168 - jQuery(this).dropdown('set selected', values);
4169 - });
4170 - }
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 + }
4171 5168 });
4172 5169
4173 5170 // MainWP Action Logs
4174 5171 jQuery(document).on('click', '.mainwp-action-log-show-more', function () {
4175 - var content = jQuery(this).closest('.item').find('.mainwp-action-log-site-response').text();
4176 - jQuery('#mainwp-action-log-response-modal').modal({
4177 - closable: false,
4178 - onHide: function () {
4179 - location.reload();
4180 - }
4181 - }).modal('show');
4182 - 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);
4183 5180 });
4184 5181
4185 5182 // MainWP Show Response
4186 5183 jQuery(document).on('click', '.mainwp-show-response', function () {
4187 - var content = jQuery('#mainwp-response-data-container').attr('resp-data');
4188 - jQuery('#mainwp-response-data-modal').modal({
4189 - closable: false,
4190 - onHide: function () {
4191 - jQuery('#mainwp-response-data-modal .content-response').text('');
4192 - }
4193 - }).modal('show');
4194 - 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);
4195 5192 });
4196 5193
4197 5194 // Copy to clipboard for response modals.
4198 -jQuery(document).on('click', '.mainwp-response-copy-button', function () {
4199 - var modal = jQuery(this).closest('.ui.modal');
4200 - var data = jQuery(modal).find('.content.content-response').text();
4201 - var $temp_txtarea = jQuery('<textarea style="opacity:0">');
4202 - jQuery('body').append($temp_txtarea);
4203 - $temp_txtarea.val(data).trigger("select");
4204 - try {
4205 - var successful = document.execCommand('copy');
4206 - var msg = successful ? 'successful' : 'unsuccessful';
4207 - console.log('Copying text command was ' + msg);
4208 - } catch (err) {
4209 - console.log('Oops, unable to copy');
4210 - }
4211 - $temp_txtarea.remove();
4212 - return false;
5195 +jQuery(document).on('click', '.mainwp-response-copy-button', function (event) {
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;
4213 5204 });
4214 5205
4215 -jQuery(document).ready(function () {
4216 - if (typeof postboxes !== "undefined" && typeof mainwp_postbox_page !== "undefined") {
4217 - postboxes.add_postbox_toggles(mainwp_postbox_page);
4218 - }
4219 - mainwp_setCookie();
4220 - mainwp_getCookie();
5206 +jQuery(function () {
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();
4221 5212 });
4222 5213
4223 5214 jQuery(document).on('click', '.close.icon', function () {
4224 - jQuery(this).parent().hide();
5215 + jQuery(this).parent().hide();
4225 5216 });
4226 5217
4227 5218 /*
4228 5219 * to compatible
@@ -4227,95 +5218,507 @@
4227 5218 /*
4228 5219 * to compatible
4229 5220 */
4230 5221 function mainwp_setCookie() {
4231 - return false;
5222 + return false;
4232 5223 }
4233 5224
4234 5225 function mainwp_getCookie() {
4235 - return false;
5226 + return false;
4236 5227 }
4237 5228
4238 -mainwp_setttings_fields_indicator_show = function () {
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;
5233 + }
5234 + // for each header indicator.
5235 + jQuery('.settings-field-header-indicator').each(function () {
5236 + mainwp_setttings_fields_indicator_specific_show(this);
5237 + });
5238 +}
4239 5239
4240 - // show saved indicator status.
4241 - // if (undefined !== mainwp_settings_saved_menu_indicator_status && '' !== mainwp_settings_saved_menu_indicator_status) {
4242 - // var saved_status = JSON.parse(mainwp_settings_saved_menu_indicator_status);
4243 - // for (const [key, value] of Object.entries(saved_status)) {
4244 - // if (key !== undefined && key !== '' && jQuery('.settings-field-menu-indicator[menu-indicator="' + key + '"]').length) {
4245 - // if ('1' == value) {
4246 - // jQuery('.settings-field-menu-indicator[menu-indicator="' + key + '"]').attr('style', 'display:inline-block;');
4247 - // jQuery('.settings-field-menu-indicator[menu-indicator="' + key + '"]').attr('indicator-status', 'show');
4248 - // }
4249 - // }
4250 - // }
4251 - // }
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 +}
4252 5247
4253 - // if (jQuery('.settings-field-menu-indicator[menu-indicator-active="1"]').length) {
4254 - // var current_menu_active = jQuery('.settings-field-menu-indicator[menu-indicator-active="1"]').attr('menu-indicator');
4255 - // var current_menu_status = 'show' == jQuery('.settings-field-menu-indicator[menu-indicator-active="1"]').attr('indicator-status') ? 1 : 0;
4256 - // var val_indi = jQuery('.settings-field-icon-indicator[indicator-status="show"]').length > 0 ? 1 : 0;
4257 - // if (current_menu_status != val_indi) {
4258 - // mainwp_setttings_fields_save_indicator_status(current_menu_active, val_indi);
4259 - // if (val_indi) {
4260 - // jQuery('.settings-field-menu-indicator[menu-indicator="' + current_menu_active + '"]').attr('style', 'display:inline-block;');
4261 - // jQuery('.settings-field-menu-indicator[menu-indicator="' + current_menu_active + '"]').attr('indicator-status', 'show');
4262 - // } else {
4263 - // jQuery('.settings-field-menu-indicator[menu-indicator="' + current_menu_active + '"]').attr('style', 'display:none;');
4264 - // jQuery('.settings-field-menu-indicator[menu-indicator="' + current_menu_active + '"]').attr('indicator-status', 'hide');
4265 - // }
4266 - // }
4267 - // }
4268 5248
4269 - // for each header indicator.
4270 - jQuery('.settings-field-header-indicator').each(function () {
4271 - var cls = jQuery(this).attr('field-indicator-wrapper-class');
4272 - let menu_indi = jQuery(this).attr('menu-indicator');
4273 - if ('' != cls && jQuery('.' + cls + ' .settings-field-icon-indicator').length > 0) {
4274 - jQuery(this).attr('style', 'display:inline-block;');
4275 - jQuery(this).attr('indicator-status', 'show');
4276 - if (menu_indi !== undefined && menu_indi !== '' && jQuery('.settings-field-menu-indicator[menu-indicator="' + menu_indi + '"]').length) {
4277 - jQuery('.settings-field-menu-indicator[menu-indicator="' + menu_indi + '"]').attr('style', 'display:inline-block;');
4278 - }
5249 +jQuery(function ($) {
5250 + if (jQuery('.mainwp-ui-page').length) {
5251 + mainwp_setttings_fields_indicator_show();
4279 5252 }
4280 - });
5253 +
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 + });
5258 +
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 + }
5285 + }
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 + }
5307 + }
5308 +});
5309 +
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 + }
5319 + }
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 + })();
5376 + }
5377 +
5378 +});
5379 +
5380 +let mainwp_overview_gridstack_save_layout = function (item_id, grid) {
5381 +
5382 + if (!grid?.engine?.nodes) {
5383 + return;
5384 + }
5385 +
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;
5406 + }
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 () { });
4281 5417 }
4282 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();
4283 5431
4284 -mainwp_setttings_fields_save_indicator_status = function (menu_indi, val_indi) {
4285 - var data = mainwp_secure_data({
4286 - action: 'mainwp_status_saving',
4287 - status: 'save_indicator_values',
4288 - name: menu_indi,
4289 - value: val_indi
4290 - });
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 + });
4291 5442
4292 - jQuery.ajax({
4293 - type: 'POST',
4294 - url: ajaxurl,
4295 - data: data,
4296 - success: function () {
4297 - // ok.
4298 - },
4299 - });
4300 5443 }
4301 5444
5445 +
4302 5446 jQuery(document).ready(function () {
4303 - if (jQuery('.mainwp-ui-page').length) {
4304 - mainwp_setttings_fields_indicator_show();
4305 - }
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 + });
4306 5454 });
4307 5455
4308 -mainwp_common_filter_hide_segments_message = function () {
4309 - jQuery('#mainwp-common-filter-edit-segment-status').removeClass('red green').hide();
4310 -};
4311 -mainwp_common_filter_show_segments_modal = function (loadSeg) {
4312 - mainwp_common_filter_hide_segments_message();
4313 - jQuery('#mainwp-common-filter-segment-modal').modal({
4314 - allowMultiple: false,
4315 - onShow: function () {
4316 - if (typeof loadSeg !== "undefined" && loadSeg) {
4317 - mainwp_common_filter_load_segments();
4318 - }
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 +
5463 +jQuery(function ($) {
5464 +
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?");
5472 + }
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 + });
5535 +});
5536 +
5537 +
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');
4319 5559 }
4320 - }).modal('show');
4321 -};
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);
5570 + }
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');
5606 + }
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();
5622 + }
5623 +
5624 + /* ---------- Storage ---------- */
5625 +
5626 + get storageKey() {
5627 + return `${this.options.storagePrefix}:${this.tableId}`;
5628 + }
5629 +
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 +}