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