PluginProbe
MainWP Dashboard: Self-hosted WordPress Management for Agencies / 5.2.1
MainWP Dashboard: Self-hosted WordPress Management for Agencies v5.2.1
6.2 6.1.8 6.1.7 6.1.6 6.1.5 6.1.4 6.1.3 6.1.2 6.1.1 6.1 6.0.12 6.0.11 4.6.0.1 5.0 5.0.1 5.0.2 5.0.3 5.0.3.1 5.0.3.2 5.1 5.1.1 5.2 5.2.1 5.2.2 5.3 All 153 releases
mainwp / assets / js / mainwp.js

mainwp.js in MainWP Dashboard: Self-hosted WordPress Management for Agencies 5.2.1, at assets/js/mainwp.js

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