PluginProbe
MainWP Dashboard: Self-hosted WordPress Management for Agencies / 4.0.5
MainWP Dashboard: Self-hosted WordPress Management for Agencies v4.0.5
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
← All changes | class/class-mainwp-db.php +1702 -2260 5.14.0.5 View file →
@@ -1,2569 +1,2011 @@
1 1 <?php
2 -/**
3 - * MainWP Database Controller
4 - *
5 - * This file handles all interactions with the DB.
6 - *
7 - * @package MainWP/Dashboard
8 - */
9 2
10 -namespace MainWP\Dashboard;
3 +class MainWP_DB {
11 4
12 -/**
13 - * Class MainWP_DB
14 - *
15 - * @package MainWP\Dashboard
16 - *
17 - * @uses \MainWP\Dashboard\MainWP_DB_Base
18 - */
19 -class MainWP_DB extends MainWP_DB_Base { // phpcs:ignore Generic.Classes.OpeningBraceSameLine.ContentAfterBrace -- NOSONAR.
5 + //Config
6 + private $mainwp_db_version = '8.14';
7 + //Private
8 + private $table_prefix;
9 + //Singleton
10 + /** @var $instance MainWP_DB */
11 + private static $instance = null;
20 12
21 - // phpcs:disable WordPress.DB.RestrictedFunctions, WordPress.DB.PreparedSQL.NotPrepared, Generic.Metrics.CyclomaticComplexity -- This is the only way to achieve desired results, pull request solutions appreciated.
13 + /** @var $wpdb wpdb */
14 + private $wpdb;
22 15
23 - /**
24 - * Private static variable to hold the single instance of the class.
25 - *
26 - * @static
27 - *
28 - * @var mixed Default null
29 - */
30 - private static $instance = null;
16 + /**
17 + * @static
18 + * @return MainWP_DB
19 + */
20 + static function Instance() {
21 + if ( MainWP_DB::$instance == null ) {
22 + MainWP_DB::$instance = new MainWP_DB();
23 + }
31 24
32 - /**
33 - * Private static variable to hold the single instance.
34 - *
35 - * @static
36 - *
37 - * @var mixed Default null
38 - */
39 - private static $general_options = null;
25 + MainWP_DB::$instance->test_connection();
40 26
41 - /**
42 - * Possible options.
43 - *
44 - * @var array $possible_options
45 - */
46 - private static $possible_options = array(
47 - 'plugin_upgrades',
48 - 'theme_upgrades',
49 - 'premium_upgrades',
50 - 'plugins',
51 - 'themes',
52 - 'dtsSync',
53 - 'version',
54 - 'sync_errors',
55 - 'ignored_plugins',
56 - 'wp_upgrades',
57 - 'site_info',
58 - 'client',
59 - 'signature_algo',
60 - 'verify_method',
61 - 'pubkey',
62 - );
27 + return MainWP_DB::$instance;
28 + }
63 29
64 - /**
65 - * Create public static instance.
66 - *
67 - * @static
68 - *
69 - * @return MainWP_DB
70 - */
71 - public static function instance() {
72 - if ( null === static::$instance ) {
73 - static::$instance = new self();
74 - }
30 + //Constructor
31 + function __construct() {
32 + /** @var $this ->wpdb wpdb */
33 + global $wpdb;
75 34
76 - static::$instance->test_connection();
35 + $this->wpdb = &$wpdb;
36 + $this->table_prefix = $wpdb->prefix . 'mainwp_';
37 + }
77 38
78 - return static::$instance;
79 - }
39 + private function test_connection() {
40 + if ( !self::ping( $this->wpdb->dbh ) ) {
41 + MainWP_Logger::Instance()->info( __( 'Trying to reconnect WordPress database connection...', 'mainwp' ) );
42 + $this->wpdb->db_connect();
43 + }
44 + }
80 45
81 - /**
82 - * Get wp_options database table view.
83 - *
84 - * @param array $fields Extra option fields.
85 - * @param bool $default_value Whether or not to get default option fields.
86 - *
87 - * @return array wp_options view.
88 - */
89 - public function get_option_view( $fields = array(), $default_value = true ) {
46 + private function tableName( $suffix, $tablePrefix = null ) {
47 + return ( $tablePrefix == null ? $this->table_prefix : $tablePrefix ) . $suffix;
48 + }
90 49
91 - if ( ! is_array( $fields ) ) {
92 - $fields = array();
93 - }
50 + //Installs new DB
51 + function install() {
52 + //get_site_option is multisite aware!
53 + $currentVersion = get_site_option( 'mainwp_db_version' );
94 54
95 - $view = '(SELECT intwp.id AS wpid ';
55 + if ( empty( $currentVersion ) ) {
56 + //set_transient( '_mainwp_activation_redirect', 1, 30 );
57 + update_option( 'mainwp_run_quick_setup', 'yes' );
58 + MainWP_Utility::update_option( 'mainwp_enableLegacyBackupFeature', 0 );
59 + } else if ( false === get_option( 'mainwp_enableLegacyBackupFeature' ) ) {
60 + MainWP_Utility::update_option( 'mainwp_enableLegacyBackupFeature', 1 );
61 + }
96 62
97 - if ( empty( $fields ) || $default_value ) {
98 - $view .= ',(SELECT recent_comments.value FROM ' . $this->table_name( 'wp_options' ) . ' recent_comments WHERE recent_comments.wpid = intwp.id AND recent_comments.name = "recent_comments" LIMIT 1) AS recent_comments,
99 - (SELECT recent_posts.value FROM ' . $this->table_name( 'wp_options' ) . ' recent_posts WHERE recent_posts.wpid = intwp.id AND recent_posts.name = "recent_posts" LIMIT 1) AS recent_posts,
100 - (SELECT recent_pages.value FROM ' . $this->table_name( 'wp_options' ) . ' recent_pages WHERE recent_pages.wpid = intwp.id AND recent_pages.name = "recent_pages" LIMIT 1) AS recent_pages,
101 - (SELECT phpversion.value FROM ' . $this->table_name( 'wp_options' ) . ' phpversion WHERE phpversion.wpid = intwp.id AND phpversion.name = "phpversion" LIMIT 1) AS phpversion,
102 - (SELECT added_timestamp.value FROM ' . $this->table_name( 'wp_options' ) . ' added_timestamp WHERE added_timestamp.wpid = intwp.id AND added_timestamp.name = "added_timestamp" LIMIT 1) AS added_timestamp,
103 - (SELECT wp_upgrades.value FROM ' . $this->table_name( 'wp_options' ) . ' wp_upgrades WHERE wp_upgrades.wpid = intwp.id AND wp_upgrades.name = "wp_upgrades" LIMIT 1) AS wp_upgrades ';
104 - }
63 + $rslt = MainWP_DB::Instance()->query( "SHOW TABLES LIKE '" . $this->tableName( 'wp' ) . "'" );
64 + if ( @MainWP_DB::num_rows( $rslt ) == 0 ) {
65 + $currentVersion = false;
66 + }
105 67
106 - if ( ! in_array( 'signature_algo', $fields ) ) {
107 - $fields[] = 'signature_algo';
108 - }
68 + if ( $currentVersion == $this->mainwp_db_version ) {
69 + return;
70 + }
109 71
110 - if ( ! in_array( 'verify_method', $fields ) ) {
111 - $fields[] = 'verify_method';
112 - }
72 + $charset_collate = $this->wpdb->get_charset_collate();
113 73
114 - if ( ! in_array( 'cust_site_icon_info', $fields, true ) ) {
115 - $fields[] = 'cust_site_icon_info';
116 - }
74 + $sql = array();
75 + $tbl = 'CREATE TABLE ' . $this->tableName( 'wp' ) . ' (
76 + id int(11) NOT NULL auto_increment,
77 + userid int(11) NOT NULL,
78 + adminname text NOT NULL,
79 + name text NOT NULL,
80 + url text NOT NULL,
81 + pubkey text NOT NULL,
82 + privkey text NOT NULL,
83 + nossl tinyint(1) NOT NULL,
84 + nosslkey text NOT NULL,
85 + siteurl text NOT NULL,
86 + ga_id text NOT NULL,
87 + gas_id int(11) NOT NULL,
88 + offline_checks text NOT NULL,
89 + offline_checks_last int(11) NOT NULL,
90 + offline_check_result int(11) NOT NULL,
91 + http_response_code int(11) NOT NULL DEFAULT 0,
92 + note text NOT NULL,
93 + note_lastupdate int(11) NOT NULL DEFAULT 0,
94 + statsUpdate int(11) NOT NULL,
95 + pagerank int(11) NOT NULL,
96 + indexed int(11) NOT NULL,
97 + alexia int(11) NOT NULL,
98 + pagerank_old int(11) DEFAULT NULL,
99 + indexed_old int(11) DEFAULT NULL,
100 + alexia_old int(11) DEFAULT NULL,
101 + directories longtext NOT NULL,
102 + plugin_upgrades longtext NOT NULL,
103 + theme_upgrades longtext NOT NULL,
104 + translation_upgrades longtext NOT NULL,
105 + premium_upgrades longtext NOT NULL,
106 + securityIssues longtext NOT NULL,
107 + themes longtext NOT NULL,
108 + ignored_themes longtext NOT NULL,
109 + plugins longtext NOT NULL,
110 + ignored_plugins longtext NOT NULL,
111 + pages longtext NOT NULL,
112 + users longtext NOT NULL,
113 + categories longtext NOT NULL,
114 + pluginDir text NOT NULL,
115 + automatic_update tinyint(1) NOT NULL,
116 + backup_before_upgrade tinyint(1) NOT NULL DEFAULT 2,
117 + last_db_backup_size int(11) NOT NULL,
118 + backups text NOT NULL,
119 + mainwpdir int(11) NOT NULL,
120 + loadFilesBeforeZip tinyint(1) NOT NULL DEFAULT 1,
121 + is_ignoreCoreUpdates tinyint(1) NOT NULL DEFAULT 0,
122 + is_ignorePluginUpdates tinyint(1) NOT NULL DEFAULT 0,
123 + is_ignoreThemeUpdates tinyint(1) NOT NULL DEFAULT 0,
124 + verify_certificate tinyint(1) NOT NULL DEFAULT 1,
125 + force_use_ipv4 tinyint(1) NOT NULL DEFAULT 0,
126 + ssl_version tinyint(1) NOT NULL DEFAULT 0,
127 + ip text NOT NULL DEFAULT "",
128 + uniqueId text NOT NULL,
129 + maximumFileDescriptorsOverride tinyint(1) NOT NULL DEFAULT 0,
130 + maximumFileDescriptorsAuto tinyint(1) NOT NULL DEFAULT 1,
131 + maximumFileDescriptors int(11) NOT NULL DEFAULT 150,
132 + http_user text NOT NULL DEFAULT "",
133 + http_pass text NOT NULL DEFAULT "",
134 + wpe tinyint(1) NOT NULL,
135 + is_staging tinyint(1) NOT NULL DEFAULT 0,
136 + KEY idx_userid (userid)';
137 + if ( $currentVersion == '' ) {
138 + $tbl .= ',
139 + PRIMARY KEY (id) ';
140 + }
141 + $tbl .= ') ' . $charset_collate;
142 + $sql[] = $tbl;
117 143
118 - if ( is_array( $fields ) ) {
119 - foreach ( $fields as $field ) {
120 - if ( empty( $field ) ) {
121 - continue;
122 - }
123 - $view .= ', ';
124 - $view .= '(SELECT ' . $this->escape( $field ) . '.value FROM ' . $this->table_name( 'wp_options' ) . ' ' . $this->escape( $field ) . ' WHERE ' . $this->escape( $field ) . '.wpid = intwp.id AND ' . $this->escape( $field ) . '.name = "' . $this->escape( $field ) . '" LIMIT 1) AS ' . $this->escape( $field );
125 - }
126 - }
144 + $tbl = 'CREATE TABLE ' . $this->tableName( 'wp_sync' ) . ' (
145 + wpid int(11) NOT NULL,
146 + version text NOT NULL DEFAULT "",
147 + sync_errors longtext NOT NULL DEFAULT "",
148 + uptodate longtext NOT NULL DEFAULT "",
149 + dtsAutomaticSync int(11) NOT NULL DEFAULT 0,
150 + dtsAutomaticSyncStart int(11) NOT NULL DEFAULT 0,
151 + dtsSync int(11) NOT NULL DEFAULT 0,
152 + dtsSyncStart int(11) NOT NULL DEFAULT 0,
153 + totalsize int(11) NOT NULL DEFAULT 0,
154 + dbsize int(11) NOT NULL DEFAULT 0,
155 + extauth text NOT NULL DEFAULT "",
156 + last_post_gmt int(11) NOT NULL DEFAULT 0,
157 + KEY idx_wpid (wpid)) ' . $charset_collate;
158 + $sql[] = $tbl;
127 159
128 - $view .= ' FROM ' . $this->table_name( 'wp' ) . ' intwp)';
160 + $tbl = 'CREATE TABLE ' . $this->tableName( 'wp_options' ) . ' (
161 + wpid int(11) NOT NULL,
162 + name text NOT NULL DEFAULT "",
163 + value longtext NOT NULL DEFAULT "",
164 + KEY idx_wpid (wpid)) ' . $charset_collate;
165 + $sql[] = $tbl;
129 166
130 - return $view;
131 - }
167 + $tbl = 'CREATE TABLE ' . $this->tableName( 'wp_settings_backup' ) . ' (
168 + wpid int(11) NOT NULL,
169 + archiveFormat text NOT NULL,
170 + KEY idx_wpid (wpid)) ' . $charset_collate;
171 + $sql[] = $tbl;
132 172
133 - /**
134 - * Method get_select_groups_belong().
135 - *
136 - * @return string sql.
137 - */
138 - public function get_select_groups_belong() {
139 - return ', ( SELECT GROUP_CONCAT(grbl.name ORDER BY grbl.name SEPARATOR ",")
140 - FROM ' . $this->table_name( 'wp_group' ) . ' wpgrbl
141 - JOIN ' . $this->table_name( 'group' ) . ' grbl ON grbl.id = wpgrbl.groupid WHERE wpgrbl.wpid = wp.id ) as wpgroups_belong,
142 - ( SELECT GROUP_CONCAT(grbl.id ORDER BY grbl.name SEPARATOR ",") FROM ' . $this->table_name( 'wp_group' ) . ' wpgrbl
143 - JOIN ' . $this->table_name( 'group' ) . ' grbl ON grbl.id = wpgrbl.groupid WHERE wpgrbl.wpid = wp.id ) as wpgroupids_belong,
144 - ( SELECT GROUP_CONCAT(grbl.color ORDER BY grbl.name SEPARATOR ",") FROM ' . $this->table_name( 'wp_group' ) . ' wpgrbl
145 - JOIN ' . $this->table_name( 'group' ) . ' grbl ON grbl.id = wpgrbl.groupid WHERE wpgrbl.wpid = wp.id ) as wpgroupcolors_belong ';
146 - }
173 + $tbl = 'CREATE TABLE ' . $this->tableName( 'tips' ) . ' (
174 + id int(11) NOT NULL auto_increment,
175 + seq int(11) NOT NULL,
176 + content text NOT NULL';
177 + if ( $currentVersion == '' ) {
178 + $tbl .= ',
179 + PRIMARY KEY (id) ';
180 + }
181 + $tbl .= ') ' . $charset_collate;
182 + $sql[] = $tbl;
147 183
148 - /**
149 - * Get connected child sites.
150 - *
151 - * @param array $sites_ids Websites ids - option field.
152 - *
153 - * @return array $connected_sites Array of connected sites.
154 - */
155 - public function get_connected_websites( $sites_ids = false ) {
156 - $where = $this->get_sql_where_allow_access_sites( 'wp' );
184 + $tbl = 'CREATE TABLE ' . $this->tableName( 'users' ) . " (
185 + userid int(11) NOT NULL,
186 + user_email text NOT NULL DEFAULT '',
187 + tips tinyint(1) NOT NULL DEFAULT '1',
188 + offlineChecksOnlineNotification tinyint(1) NOT NULL DEFAULT '0',
189 + heatMap tinyint(1) NOT NULL DEFAULT '0',
190 + ignored_plugins longtext NOT NULL DEFAULT '',
191 + trusted_plugins longtext NOT NULL DEFAULT '',
192 + trusted_plugins_notes longtext NOT NULL DEFAULT '',
193 + ignored_themes longtext NOT NULL DEFAULT '',
194 + trusted_themes longtext NOT NULL DEFAULT '',
195 + trusted_themes_notes longtext NOT NULL DEFAULT '',
196 + site_view tinyint(1) NOT NULL DEFAULT '0',
197 + pluginDir text NOT NULL DEFAULT '',
198 + dismissed_plugins longtext NOT NULL DEFAULT '',
199 + dismissed_themes longtext NOT NULL DEFAULT ''";
200 + if ( $currentVersion == '' ) {
201 + $tbl .= ',
202 + PRIMARY KEY (userid) ';
203 + }
204 + $tbl .= ') ' . $charset_collate;
205 + $sql[] = $tbl;
157 206
158 - $sql = 'SELECT wp.*,wp_sync.*
159 - FROM ' . $this->table_name( 'wp' ) . ' wp
160 - JOIN ' . $this->table_name( 'wp_sync' ) . ' wp_sync
161 - ON wp.id = wp_sync.wpid
162 - WHERE (wp_sync.sync_errors IS NOT NULL) AND (wp_sync.sync_errors = "") ' .
163 - $where;
207 + $tbl = 'CREATE TABLE ' . $this->tableName( 'group' ) . ' (
208 + id int(11) NOT NULL auto_increment,
209 + userid int(11) NOT NULL,
210 + name text NOT NULL';
211 + if ( $currentVersion == '' ) {
212 + $tbl .= ',
213 + PRIMARY KEY (id) ';
214 + }
215 + $tbl .= ') ' . $charset_collate;
216 + $sql[] = $tbl;
164 217
165 - $websites = $this->wpdb->get_results( $sql );
166 - $connected_sites = array();
167 - if ( $websites ) {
168 - foreach ( $websites as $website ) {
218 + $sql[] = 'CREATE TABLE ' . $this->tableName( 'wp_group' ) . ' (
219 + wpid int(11) NOT NULL,
220 + groupid int(11) NOT NULL,
221 + KEY idx_wpid (wpid),
222 + KEY idx_groupid (groupid)
223 + ) ' . $charset_collate;
169 224
170 - if ( ! empty( $sites_ids ) && ! in_array( $website->id, $sites_ids ) ) {
171 - continue;
172 - }
225 + $tbl = 'CREATE TABLE ' . $this->tableName( 'wp_backup_progress' ) . ' (
226 + task_id int(11) NOT NULL,
227 + wp_id int(11) NOT NULL,
228 + dtsFetched int(11) NOT NULL DEFAULT 0,
229 + fetchResult text NOT NULL DEFAULT "",
230 + downloadedDB text NOT NULL DEFAULT "",
231 + downloadedFULL text NOT NULL DEFAULT "",
232 + downloadedDBComplete tinyint(1) NOT NULL DEFAULT 0,
233 + downloadedFULLComplete tinyint(1) NOT NULL DEFAULT 0,
234 + removedFiles tinyint(1) NOT NULL DEFAULT 0,
235 + attempts int(11) NOT NULL DEFAULT 0,
236 + last_error text NOT NULL DEFAULT "",
237 + pid int(11) NOT NULL DEFAULT 0,
238 + KEY idx_task_id (task_id)
239 + ) ' . $charset_collate;
240 + $sql[] = $tbl;
173 241
174 - $connected_sites[] = array(
175 - 'id' => $website->id,
176 - 'name' => $website->name,
177 - 'url' => $website->url,
178 - );
179 - }
180 - }
181 - return $connected_sites;
182 - }
242 + $tbl = 'CREATE TABLE ' . $this->tableName( 'wp_backup' ) . ' (
243 + id int(11) NOT NULL auto_increment,
244 + userid int(11) NOT NULL,
245 + name text NOT NULL,
246 + schedule text NOT NULL,
247 + type text NOT NULL,
248 + exclude text NOT NULL,
249 + sites text NOT NULL,
250 + groups text NOT NULL,
251 + last int(11) NOT NULL,
252 + last_run int(11) NOT NULL,
253 + lastStartNotificationSent int(11) NOT NULL DEFAULT 0,
254 + last_run_manually int(11) NOT NULL,
255 + completed_sites text NOT NULL,
256 + completed int(11) NOT NULL,
257 + backup_errors text NOT NULL,
258 + subfolder text NOT NULL,
259 + filename text NOT NULL,
260 + paused tinyint(1) NOT NULL,
261 + template tinyint(1) DEFAULT 0,
262 + excludebackup tinyint(1) DEFAULT 0,
263 + excludecache tinyint(1) DEFAULT 0,
264 + excludenonwp tinyint(1) DEFAULT 0,
265 + excludezip tinyint(1) DEFAULT 0,
266 + archiveFormat text NOT NULL,
267 + loadFilesBeforeZip tinyint(1) NOT NULL DEFAULT 1,
268 + maximumFileDescriptorsOverride tinyint(1) NOT NULL DEFAULT 0,
269 + maximumFileDescriptorsAuto tinyint(1) NOT NULL DEFAULT 1,
270 + maximumFileDescriptors int(11) NOT NULL DEFAULT 150';
271 + if ( $currentVersion == '' ) {
272 + $tbl .= ',
273 + PRIMARY KEY (id) ';
274 + }
275 + $tbl .= ') ' . $charset_collate;
276 + $sql[] = $tbl;
183 277
184 - /**
185 - * Get disconnected child sites.
186 - *
187 - * @param array $sites_ids Websites ids - option field.
188 - *
189 - * @return array $disc_sites Array of disonnected sites.
190 - */
191 - public function get_disconnected_websites( $sites_ids = false ) {
192 - $where = $this->get_sql_where_allow_access_sites( 'wp' );
278 + $tbl = 'CREATE TABLE ' . $this->tableName( 'request_log' ) . ' (
279 + id int(11) NOT NULL auto_increment,
280 + wpid int(11) NOT NULL,
281 + ip text NOT NULL DEFAULT "",
282 + subnet text NOT NULL DEFAULT "",
283 + micro_timestamp_stop DECIMAL( 12, 2 ) NOT NULL DEFAULT 0,
284 + micro_timestamp_start DECIMAL( 12, 2 ) NOT NULL DEFAULT 0';
285 + if ( $currentVersion == '' || version_compare( $currentVersion, '5.7', '<=' ) ) {
286 + $tbl .= ',
287 + PRIMARY KEY (id) ';
288 + }
289 + $tbl .= ') ' . $charset_collate . ";";
290 + $sql[] = $tbl;
193 291
194 - $sql = 'SELECT wp.*,wp_sync.*
195 - FROM ' . $this->table_name( 'wp' ) . ' wp
196 - JOIN ' . $this->table_name( 'wp_sync' ) . ' wp_sync
197 - ON wp.id = wp_sync.wpid
198 - WHERE (wp_sync.sync_errors IS NOT NULL) AND (wp_sync.sync_errors <> "") ' .
199 - $where;
292 + require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
293 + foreach ( $sql as $query ) {
294 + dbDelta( $query );
295 + }
200 296
201 - $websites = $this->wpdb->get_results( $sql );
202 - $disc_sites = array();
203 - if ( $websites ) {
204 - foreach ( $websites as $website ) {
297 + // /** @var $this->wpdb wpdb */
298 + // $this->wpdb->query('CREATE OR REPLACE VIEW ' . $this->tableName('wp_optionview') . ' AS
299 + // SELECT intwp.id AS wpid,
300 + // recent_comments.value AS recent_comments,
301 + // recent_posts.value AS recent_posts,
302 + // recent_pages.value AS recent_pages
303 + // FROM ' . $this->tableName('wp') . ' intwp
304 + // LEFT JOIN ' . $this->tableName('wp_options') . ' recent_comments ON recent_comments.wpid = intwp.id AND recent_comments.name = "recent_comments"
305 + // LEFT JOIN ' . $this->tableName('wp_options') . ' recent_posts ON recent_posts.wpid = intwp.id AND recent_posts.name = "recent_posts"
306 + // LEFT JOIN ' . $this->tableName('wp_options') . ' recent_pages ON recent_pages.wpid = intwp.id AND recent_pages.name = "recent_pages"');
205 307
206 - if ( ! empty( $sites_ids ) && ! in_array( $website->id, $sites_ids ) ) {
207 - continue;
208 - }
308 + $this->post_update();
209 309
210 - $disc_sites[] = array(
211 - 'id' => $website->id,
212 - 'name' => $website->name,
213 - 'url' => $website->url,
214 - );
215 - }
216 - }
217 - return $disc_sites;
218 - }
310 + if ( !is_multisite() ) {
311 + MainWP_Utility::update_option( 'mainwp_db_version', $this->mainwp_db_version );
312 + } else {
313 + update_site_option( 'mainwp_db_version', $this->mainwp_db_version );
314 + }
315 + }
219 316
220 - /**
221 - * Get child site count.
222 - *
223 - * @param null $userId Current user ID.
224 - * @param bool $all_access Check if user has access to all sites.
225 - *
226 - * @return int Child site count.
227 - *
228 - * @uses \MainWP\Dashboard\MainWP_System::is_multi_user()
229 - */
230 - public function get_websites_count( $userId = null, $all_access = false ) {
231 - static $total_sites;
232 - if ( null !== $total_sites ) { // NOSONAR -- static value.
233 - return $total_sites;
234 - }
235 - if ( ( null === $userId ) && MainWP_System::instance()->is_multi_user() ) {
317 + //Check for update - if required, update..
318 + function update() {
236 319
237 - /**
238 - * Current user global.
239 - *
240 - * @global string
241 - */
242 - global $current_user;
320 + }
243 321
244 - $userId = $current_user->ID;
322 + function getOptionView( $extra = array()) {
323 + $view = '(SELECT intwp.id AS wpid,
324 + (SELECT recent_comments.value FROM ' . $this->tableName( 'wp_options' ) . ' recent_comments WHERE recent_comments.wpid = intwp.id AND recent_comments.name = "recent_comments" LIMIT 1) AS recent_comments,
325 + (SELECT recent_posts.value FROM ' . $this->tableName( 'wp_options' ) . ' recent_posts WHERE recent_posts.wpid = intwp.id AND recent_posts.name = "recent_posts" LIMIT 1) AS recent_posts,
326 + (SELECT recent_pages.value FROM ' . $this->tableName( 'wp_options' ) . ' recent_pages WHERE recent_pages.wpid = intwp.id AND recent_pages.name = "recent_pages" LIMIT 1) AS recent_pages,
327 + (SELECT phpversion.value FROM ' . $this->tableName( 'wp_options' ) . ' phpversion WHERE phpversion.wpid = intwp.id AND phpversion.name = "phpversion" LIMIT 1) AS phpversion,
328 + (SELECT wp_upgrades.value FROM ' . $this->tableName( 'wp_options' ) . ' wp_upgrades WHERE wp_upgrades.wpid = intwp.id AND wp_upgrades.name = "wp_upgrades" LIMIT 1) AS wp_upgrades ';
329 +
330 + if (is_array($extra)) {
331 + foreach($extra as $field) {
332 + if (empty($field))
333 + continue;
334 + $view .= ', ';
335 + $view .= '(SELECT ' . $this->escape($field) . '.value FROM ' . $this->tableName( 'wp_options' ) . ' ' . $this->escape($field) . ' WHERE ' . $this->escape($field) . '.wpid = intwp.id AND ' . $this->escape($field) . '.name = "' . $this->escape($field) . '" LIMIT 1) AS ' . $this->escape($field);
336 + }
245 337 }
246 - $where = ( null === $userId ? '' : ' wp.userid = ' . $userId );
247 - if ( ! $all_access ) {
248 - $where .= $this->get_sql_where_allow_access_sites( 'wp' );
249 - }
250 - $qry = 'SELECT COUNT(wp.id) FROM ' . $this->table_name( 'wp' ) . ' wp WHERE 1 ' . $where;
251 338
252 - $total = $this->wpdb->get_var( $qry );
253 - $total_sites = $total;// NOSONAR -- static value.
254 - return $total;
255 - }
339 + $view .= ' FROM ' . $this->tableName( 'wp' ) . ' intwp)';
256 340
341 + return $view;
342 + }
257 343
258 - /**
259 - * Get child sites stats count.
260 - *
261 - * @param array $params Params.
262 - */
263 - public function get_websites_stats_count( $params = array() ) {
264 - if ( ! is_array( $params ) ) {
265 - $params = array();
266 - }
344 + function post_update() {
345 + //get_site_option is multisite aware!
346 + $currentVersion = get_site_option( 'mainwp_db_version' );
347 + if ( $currentVersion === false ) {
348 + return;
349 + }
267 350
268 - if ( isset( $params['all_access'] ) ) {
269 - $all_access = ! empty( $params['all_access'] ) ? true : false;
270 - } else {
271 - $all_access = true;
272 - }
351 +// if ( version_compare( $currentVersion, '2.8', '<' ) ) {
352 +// $this->wpdb->update( $this->tableName( 'wp_backup' ), array( 'subfolder' => 'MainWP Backups/%url%/%type%/%date%' ), array( 'template' => '0' ) );
353 +// }
273 354
274 - $where = '';
275 - if ( ! $all_access ) {
276 - $where .= $this->get_sql_where_allow_access_sites( 'wp' );
277 - }
355 +// if ( version_compare( $currentVersion, '4.3', '<' ) ) {
356 +// $row = $this->wpdb->get_row( 'SELECT * FROM ' . $this->tableName( 'users' ), OBJECT );
357 +// if ( $row != null ) {
358 +// $row->userid = 0;
359 +// $this->updateUserExtension( $row );
360 +// }
361 +// }
278 362
279 - $select_stats = ' ( SELECT COUNT(wp.id) as count_all ';
280 - if ( ! empty( $params['count_disconnected'] ) ) {
281 - $select_stats .= ',( SELECT COUNT(wp_disconnected.id) FROM ' . $this->table_name( 'wp' ) . ' wp_disconnected LEFT JOIN ' . $this->table_name( 'wp_sync' ) . ' as wp_sync ';
282 - $select_stats .= ' ON wp_disconnected.id = wp_sync.wpid WHERE wp_sync.sync_errors != "" ) as count_disconnected ';
283 - }
284 - if ( ! empty( $params['count_suspended'] ) ) {
285 - $select_stats .= ',( SELECT COUNT(wp_suspended.id) FROM ' . $this->table_name( 'wp' ) . ' wp_suspended WHERE wp_suspended.suspended = 1 ) as count_suspended ';
286 - }
287 - $qry = 'SELECT * FROM ' . $select_stats;
288 - $qry .= ' FROM ' . $this->table_name( 'wp' ) . ' wp ' . $where . ' ) as wp_stats ';
363 +// if ( version_compare( $currentVersion, '5.3', '<' ) ) {
364 +// if ( MainWP_System::Instance()->isSingleUser() ) {
365 +// $row = $this->wpdb->get_row( 'SELECT * FROM ' . $this->tableName( 'ga' ), OBJECT );
366 +//
367 +// $this->wpdb->update( $this->tableName( 'ga' ), array( 'userid' => 0 ), array( 'userid' => $row->userid ) );
368 +// }
369 +// }
289 370
290 - return $this->wpdb->get_row( $qry, ARRAY_A ); //phpcs:ignore -- ok.
291 - }
371 +// if ( version_compare( $currentVersion, '6.0', '=' ) ) {
372 +// $this->wpdb->query( 'ALTER TABLE ' . $this->tableName( 'request_log' ) . ' CHANGE micro_timestamp_stop micro_timestamp_stop DECIMAL( 12, 2 ) NOT NULL DEFAULT 0' );
373 +// $this->wpdb->query( 'ALTER TABLE ' . $this->tableName( 'request_log' ) . ' CHANGE micro_timestamp_start micro_timestamp_start DECIMAL( 12, 2 ) NOT NULL DEFAULT 0' );
374 +// $this->wpdb->query( 'DELETE FROM ' . $this->tableName( 'request_log' ) . ' WHERE 1 ' );
375 +// }
292 376
293 - /**
294 - * Get Child site wp_options database table.
295 - *
296 - * @param array $website Child Site array.
297 - * @param mixed $option Child Site wp_options table name.
298 - * @param mixed $default_value default value.
299 - *
300 - * @return string|null Database query result (as string), or null on failure.
301 - */
302 - public function get_website_option( $website, $option, $default_value = null ) {
377 +// if ( version_compare( $currentVersion, '6.2', '<' ) ) {
378 +// $options = array(
379 +// 'mainwp_db_version',
380 +// //'mainwp_requests',
381 +// 'mainwp_plugin_version',
382 +// 'mainwp_upgradeVersionInfo',
383 +// 'mainwp_cron_last_offlinecheck',
384 +// 'mainwp_cron_last_updatescheck',
385 +// 'mainwp_automaticUpdate_backupChecks',
386 +// 'mainwp_updatescheck_mail_update_core_new',
387 +// 'mainwp_updatescheck_mail_update_plugins_new',
388 +// 'mainwp_updatescheck_mail_update_themes_new',
389 +// 'mainwp_updatescheck_mail_update_core',
390 +// 'mainwp_updatescheck_mail_update_plugins',
391 +// 'mainwp_updatescheck_mail_update_themes',
392 +// 'mainwp_updatescheck_mail_ignore_core',
393 +// 'mainwp_updatescheck_mail_ignore_plugins',
394 +// 'mainwp_updatescheck_mail_ignore_themes',
395 +// 'mainwp_updatescheck_mail_ignore_core_new',
396 +// 'mainwp_updatescheck_mail_ignore_plugins_new',
397 +// 'mainwp_updatescheck_mail_ignore_themes_new',
398 +// 'mainwp_updatescheck_last',
399 +// 'mainwp_updatescheck_mail_email',
400 +// 'mainwp_cron_last_ping',
401 +// 'mainwp_cron_last_backups_continue',
402 +// 'mainwp_cron_last_backups',
403 +// 'mainwp_cron_last_stats',
404 +// 'mainwp_backupsOnServer',
405 +// 'mainwp_maximumFileDescriptors',
406 +// 'mainwp_backupOnExternalSources',
407 +// 'mainwp_notificationOnBackupFail',
408 +// 'mainwp_notificationOnBackupStart',
409 +// 'mainwp_chunkedBackupTasks',
410 +// 'mainwp_maximumRequests',
411 +// 'mainwp_minimumDelay',
412 +// 'mainwp_maximumIPRequests',
413 +// 'mainwp_minimumIPDelay',
414 +// 'mainwp_extensions',
415 +// 'mainwp_api_username',
416 +// 'mainwp_api_password',
417 +// 'mainwp_extension_widget_view',
418 +// 'mainwp_news',
419 +// 'mainwp_news_timestamp',
420 +// 'mainwp_optimize',
421 +// 'mainwp_automaticDailyUpdate',
422 +// 'mainwp_backup_before_upgrade',
423 +// 'mainwp_show_language_updates',
424 +// 'mainwp_maximumPosts',
425 +// 'mainwp_maximumComments',
426 +// 'mainwp_cron_jobs',
427 +// 'mainwp_wp_cron',
428 +// );
429 +// foreach ( $options as $option ) {
430 +// MainWP_Utility::fix_option( $option );
431 +// }
432 +// }
303 433
304 - if ( is_array( $website ) ) {
305 - if ( isset( $website[ $option ] ) ) {
306 - return $website[ $option ];
307 - }
308 - $site_id = $website['id'];
309 - } elseif ( is_object( $website ) ) {
310 - if ( property_exists( $website, $option ) ) {
311 - return $website->{$option};
312 - }
313 - $site_id = $website->id;
314 - } elseif ( is_numeric( $website ) ) { // to support $site_id = 0, for global options.
315 - $site_id = $website;
316 - } else {
317 - return false;
318 - }
434 +// if ( version_compare( $currentVersion, '7.3', '<' ) ) {
435 +// //get all sites
436 +// $sites = $this->wpdb->get_results( 'SELECT id FROM ' . $this->tableName( 'wp' ) );
437 +// if ( !empty( $sites ) ) {
438 +// foreach ( $sites as $site ) {
439 +// $this->wpdb->insert( $this->tableName( 'wp_settings_backup' ), array(
440 +// 'wpid' => $site->id,
441 +// 'archiveFormat' => 'global',
442 +// ) );
443 +// }
444 +// }
445 +// }
319 446
320 - $var = $this->wpdb->get_var( $this->wpdb->prepare( 'SELECT value FROM ' . $this->table_name( 'wp_options' ) . ' WHERE wpid = %d AND name = "' . $this->escape( $option ) . '"', $site_id ) );
447 +// if ( version_compare( $currentVersion, '8', '<' ) ) {
448 +// $apiPass = get_option( 'mainwp_api_password' );
449 +// MainWP_Utility::update_option( 'mainwp_api_password', MainWP_Utility::encrypt( $apiPass, 'MainWPAPI' ) );
450 +// }
321 451
322 - if ( null === $var && null !== $default_value ) {
323 - $var = $default_value;
324 - }
325 - return $var;
326 - }
452 + if ( version_compare( $currentVersion, '8.1', '<' ) ) {
453 + //We can't split up here!
454 + $wpSyncColumns = array(
455 + 'version',
456 + 'totalsize',
457 + 'dbsize',
458 + 'extauth',
459 + 'last_post_gmt',
460 + 'uptodate',
461 + 'sync_errors',
462 + 'dtsSync',
463 + 'dtsSyncStart',
464 + 'dtsAutomaticSync',
465 + 'dtsAutomaticSyncStart',
466 + );
467 + foreach ( $wpSyncColumns as $wpSyncColumn ) {
468 + $rslts = $this->wpdb->get_results( 'SELECT id,' . $wpSyncColumn . ' FROM ' . $this->tableName( 'wp' ), ARRAY_A );
469 + if ( empty( $rslts ) ) {
470 + continue;
471 + }
327 472
328 - /**
329 - * Get child site options.
330 - *
331 - * @param array $website Child site.
332 - * @param mixed $options Child site options name.
333 - *
334 - * @return string|null Database query result (as string), or null on failure.
335 - */
336 - public function get_website_options_array( &$website, $options ) { // phpcs:ignore -- NOSONAR - complex.
473 + foreach ( $rslts as $rslt ) {
474 + $exists = $this->wpdb->get_results( 'SELECT wpid FROM ' . $this->tableName( 'wp_sync' ) . ' WHERE wpid = ' . $rslt[ 'id' ], ARRAY_A );
475 + if ( empty( $exists ) ) {
476 + $this->wpdb->insert( $this->tableName( 'wp_sync' ), array(
477 + 'wpid' => $rslt[ 'id' ],
478 + $wpSyncColumn => $rslt[ $wpSyncColumn ],
479 + ) );
480 + } else {
481 + $this->wpdb->update( $this->tableName( 'wp_sync' ), array( $wpSyncColumn => $rslt[ $wpSyncColumn ] ), array( 'wpid' => $rslt[ 'id' ] ) );
482 + }
483 + }
337 484
338 - if ( ! is_array( $options ) || empty( $options ) ) {
339 - return array();
340 - }
485 + $suppress = $this->wpdb->suppress_errors();
486 + $this->wpdb->query( 'ALTER TABLE ' . $this->tableName( 'wp' ) . ' DROP COLUMN ' . $wpSyncColumn );
487 + $this->wpdb->suppress_errors( $suppress );
488 + }
341 489
342 - if ( is_array( $website ) ) {
343 - $site_id = $website['id'];
344 - } elseif ( is_object( $website ) ) {
345 - $site_id = $website->id;
346 - } elseif ( is_numeric( $website ) ) { // to support $site_id = 0 for global options.
347 - $site_id = $website;
348 - } else {
349 - return array();
350 - }
490 + $optionColumns = array(
491 + 'last_wp_upgrades',
492 + 'last_plugin_upgrades',
493 + 'last_theme_upgrades',
494 + 'wp_upgrades',
495 + 'recent_comments',
496 + 'recent_posts',
497 + 'recent_pages',
498 + );
499 + foreach ( $optionColumns as $optionColumn ) {
500 + $rslts = $this->wpdb->get_results( 'SELECT id,' . $optionColumn . ' FROM ' . $this->tableName( 'wp' ), ARRAY_A );
501 + if ( empty( $rslts ) ) {
502 + continue;
503 + }
351 504
352 - $arr_options = array();
353 - $get_options = array();
505 + foreach ( $rslts as $rslt ) {
506 + MainWP_DB::updateWebsiteOption( (object) $rslt, $optionColumn, $rslt[ $optionColumn ] );
507 + }
354 508
355 - foreach ( $options as $option ) {
356 - if ( is_array( $website ) ) {
357 - if ( isset( $website[ $option ] ) ) {
358 - $arr_options[ $option ] = $website[ $option ];
359 - } else {
360 - $get_options[] = $option;
361 - }
362 - } elseif ( is_object( $website ) ) {
363 - if ( property_exists( $website, $option ) ) {
364 - $arr_options[ $option ] = $website->{$option};
365 - } else {
366 - $get_options[] = $option;
367 - }
368 - } else {
369 - $get_options[] = $option;
370 - }
509 + $suppress = $this->wpdb->suppress_errors();
510 + $this->wpdb->query( 'ALTER TABLE ' . $this->tableName( 'wp' ) . ' DROP COLUMN ' . $optionColumn );
511 + $this->wpdb->suppress_errors( $suppress );
512 + }
513 + }
371 514 }
372 515
373 - if ( empty( $get_options ) ) {
374 - return $arr_options; // all options.
375 - }
516 + public function getFirstSyncedSite( $userId = null ) {
517 + if ( ( $userId == null ) && MainWP_System::Instance()->isMultiUser() ) {
518 + global $current_user;
519 + $userId = $current_user->ID;
520 + }
521 + $where = ( $userId != null ) ? ' userid = ' . $userId : '';
522 + $where .= $this->getWhereAllowAccessSites( 'wp' );
523 + $qry = 'SELECT wp_sync.dtsSync FROM ' . $this->tableName( 'wp' ) . ' wp JOIN ' . $this->tableName( 'wp_sync' ) . ' wp_sync ON wp.id = wp_sync.wpid WHERE wp_sync.sync_errors = "" ' . $where . ' ORDER BY wp_sync.dtsSync ASC LIMIT 1';
376 524
377 - $options_name = implode( "','", $get_options );
378 - $options_name = "'" . $options_name . "'";
525 + return $this->wpdb->get_var( $qry );
526 + }
379 527
380 - $options_db = $this->wpdb->get_results( $this->wpdb->prepare( 'SELECT name, value FROM ' . $this->table_name( 'wp_options' ) . ' WHERE wpid = %d AND name IN (' . $options_name . ')', $site_id ) );
528 + public function getLastSyncStatus( $userId = null ) {
529 + $sql = MainWP_DB::Instance()->getSQLWebsitesForCurrentUser();
530 + $websites = MainWP_DB::Instance()->query( $sql );
381 531
382 - $fill_options = array(
383 - 'primary_lasttime_backup',
384 - );
532 + $return = array(
533 + 'sync_status' => false,
534 + 'last_sync' => 0
535 + );
385 536
386 - foreach ( (array) $options_db as $o ) {
387 - $arr_options[ $o->name ] = $o->value;
388 - if ( in_array( $o->name, $fill_options ) ) {
389 - if ( is_array( $website ) ) {
390 - if ( ! isset( $website[ $o->name ] ) ) {
391 - $website[ $o->name ] = $o->value;
392 - }
393 - } elseif ( is_object( $website ) ) {
394 - if ( ! property_exists( $website, $o->name ) ) {
395 - $website->{$o->name} = $o->value;
396 - }
397 - }
398 - }
399 - }
400 - return $arr_options;
401 - }
537 + if ( !$websites ) {
538 + $return[ 'sync_status' ] = 'all_synced';
539 + return $return;
540 + }
402 541
403 - /**
404 - * Update child site options.
405 - *
406 - * @param object $website Child site object.
407 - * @param mixed $option Option to update.
408 - * @param mixed $value Value to update with.
409 - */
410 - public function update_website_option( $website, $option, $value ) {
411 - $rslt = $this->wpdb->get_results( $this->wpdb->prepare( 'SELECT name FROM ' . $this->table_name( 'wp_options' ) . ' WHERE wpid = %d AND name = "' . $this->escape( $option ) . '"', $website->id ) );
412 - if ( empty( $rslt ) ) {
413 - $this->wpdb->insert(
414 - $this->table_name( 'wp_options' ),
415 - array(
416 - 'wpid' => $website->id,
417 - 'name' => $option,
418 - 'value' => $value,
419 - )
420 - );
421 - } else {
422 - $this->wpdb->update(
423 - $this->table_name( 'wp_options' ),
424 - array( 'value' => $value ),
425 - array(
426 - 'wpid' => $website->id,
427 - 'name' => $option,
428 - )
429 - );
430 - }
431 - }
542 + $total_sites = 0;
543 + $synced_sites = 0;
544 + $last_sync = 0;
545 + @MainWP_DB::data_seek( $websites, 0 );
546 + while ( $websites && ( $website = @MainWP_DB::fetch_object( $websites ) ) ) {
547 + if ( empty( $website ) || $website->sync_errors != '' ) {
548 + continue;
549 + }
550 + $total_sites++;
551 + if ( time() - $website->dtsSync < 60 * 60 * 24 ) {
552 + $synced_sites++;
553 + }
554 + if ( $last_sync < $website->dtsSync ) {
555 + $last_sync = $website->dtsSync;
556 + }
557 + }
432 558
559 + if ( $total_sites == $synced_sites ) {
560 + $return[ 'sync_status' ] = 'all_synced';
561 + } else if ( $synced_sites == 0 ) {
562 + $return[ 'sync_status' ] = 'not_synced';
563 + }
564 + $return[ 'last_sync' ] = $last_sync;
565 + return $return;
566 + }
433 567
434 - /**
435 - * Get general Child site option.
436 - *
437 - * @param mixed $option Child Site option name.
438 - *
439 - * @return string|null Database query result (as string), or null on failure.
440 - */
441 - private function get_general_website_option( $option ) {
568 + public function getDisconnectedWebsites() {
569 + $sql = MainWP_DB::Instance()->getSQLWebsitesForCurrentUser();
570 + $websites = MainWP_DB::Instance()->query( $sql );
442 571
443 - if ( null !== static::$general_options ) {
444 - if ( isset( static::$general_options[ $option ] ) ) {
445 - return static::$general_options[ $option ];
446 - }
447 - } else {
448 - static::$general_options[] = array();
449 - }
572 + if ( !$websites ) {
573 + return array();
574 + }
450 575
451 - $val = $this->wpdb->get_var( $this->wpdb->prepare( 'SELECT value FROM ' . $this->table_name( 'wp_options' ) . ' WHERE wpid = %d AND name = "' . $this->escape( $option ) . '"', 0 ) );
576 + $disc_sites = array();
452 577
453 - static::$general_options[ $option ] = $val;
454 - return $val;
455 - }
578 + @MainWP_DB::data_seek( $websites, 0 );
579 + while ( $websites && ( $website = @MainWP_DB::fetch_object( $websites ) ) ) {
580 + if ( empty( $website ) ) {
581 + continue;
582 + }
583 + if ( $website->sync_errors != '' ) {
584 + $disc_sites[$website->id] = $website->url;
585 + }
456 586
457 - /**
458 - * Get child site options.
459 - *
460 - * @param mixed $options Child site options name.
461 - *
462 - * @return string|null Database query result (as string), or null on failure.
463 - */
464 - public function get_general_options_array( $options ) {
587 + }
465 588
466 - if ( ! is_array( $options ) || empty( $options ) ) {
467 - return array();
468 - }
589 + return $disc_sites;
590 + }
469 591
470 - $return_options = array();
471 - if ( null !== static::$general_options ) {
472 - foreach ( static::$general_options as $opt => $val ) {
473 - if ( in_array( $opt, $options ) ) {
474 - $return_options[ $opt ] = $val;
475 - }
476 - }
477 - } else {
478 - static::$general_options[] = array();
479 - }
592 + public function getRequestsSince( $pSeconds ) {
593 + $where = $this->getWhereAllowAccessSites( 'wp' );
594 + $qry = 'SELECT count(*) FROM ' . $this->tableName( 'wp' ) . ' wp JOIN ' . $this->tableName( 'wp_sync' ) . ' wp_sync ON wp.id = wp_sync.wpid WHERE wp_sync.dtsSyncStart > ' . ( time() - $pSeconds ) . $where;
480 595
481 - $diff_options = array();
482 - foreach ( $options as $opt ) {
483 - if ( ! isset( $return_options[ $opt ] ) ) {
484 - $diff_options[] = $opt;
485 - }
486 - }
596 + return $this->wpdb->get_var( $qry );
597 + }
487 598
488 - $options_name = implode( "','", $diff_options );
489 - $options_name = "'" . $options_name . "'";
599 + //Database actions
600 + public function getWebsitesCount( $userId = null, $all_access = false ) {
601 + if ( ( $userId == null ) && MainWP_System::Instance()->isMultiUser() ) {
602 + global $current_user;
603 + $userId = $current_user->ID;
604 + }
605 + $where = ( $userId == null ? '' : ' wp.userid = ' . $userId );
606 + if ( ! $all_access ) {
607 + $where .= $this->getWhereAllowAccessSites( 'wp' );
608 + }
609 + $qry = 'SELECT COUNT(wp.id) FROM ' . $this->tableName( 'wp' ) . ' wp WHERE 1 ' . $where;
490 610
491 - $options_db = $this->wpdb->get_results( $this->wpdb->prepare( 'SELECT name, value FROM ' . $this->table_name( 'wp_options' ) . ' WHERE wpid = %d AND name IN (' . $options_name . ')', 0 ) );
611 + return $this->wpdb->get_var( $qry );
612 + }
492 613
493 - foreach ( (array) $options_db as $o ) {
494 - $return_options[ $o->name ] = $o->value;
495 - static::$general_options[ $o->name ] = $o->value;
496 - }
497 - return $return_options;
498 - }
614 + public function getWebsiteOption( $website, $option ) {
499 615
500 - /**
501 - * Update general site options.
502 - *
503 - * @param mixed $option Option to update.
504 - * @param mixed $value Value to update with.
505 - * @param string $type_value Type values: single|array.
506 - */
507 - public function update_general_option( $option, $value, $type_value = 'single' ) {
508 -
509 - if ( 'array' === $type_value ) {
510 - if ( empty( $value ) ) {
511 - $value = array();
512 - } elseif ( ! is_array( $value ) ) {
513 - return false;
616 + if ( is_array($website) ) {
617 + if ( isset($website[$option]) ) {
618 + return $website[$option];
514 619 }
515 - $value = wp_json_encode( $value );
516 - }
517 -
518 - if ( null === static::$general_options ) {
519 - static::$general_options[] = array();
520 - }
521 - static::$general_options[ $option ] = $value;
522 -
523 - $rslt = $this->wpdb->get_results( $this->wpdb->prepare( 'SELECT name FROM ' . $this->table_name( 'wp_options' ) . ' WHERE wpid = %d AND name = "' . $this->escape( $option ) . '"', 0 ) );
524 -
525 - if ( empty( $rslt ) ) {
526 - $this->wpdb->insert(
527 - $this->table_name( 'wp_options' ),
528 - array(
529 - 'wpid' => 0,
530 - 'name' => $option,
531 - 'value' => $value,
532 - )
533 - );
534 - } else {
535 - $this->wpdb->update(
536 - $this->table_name( 'wp_options' ),
537 - array( 'value' => $value ),
538 - array(
539 - 'wpid' => 0,
540 - 'name' => $option,
541 - )
542 - );
543 - }
544 - return true;
545 - }
546 -
547 - /**
548 - * Get general Child site option.
549 - *
550 - * @param mixed $opt Child Site option name.
551 - * @param string $type_value Type values: single|array.
552 - *
553 - * @return string|null Database query result (as string), or null on failure.
554 - */
555 - public function get_general_option( $opt, $type_value = 'single' ) {
556 - if ( 'single' === $type_value ) {
557 - return $this->get_general_website_option( $opt );
558 - } elseif ( 'array' === $type_value ) {
559 - $json_value = $this->get_general_website_option( $opt );
560 - if ( empty( $json_value ) ) {
561 - return array();
620 + $site_id = $website['id'];
621 + } else if ( is_object($website) ) {
622 + if ( property_exists( $website, $option ) ) {
623 + return $website->{$option};
562 624 }
563 - return json_decode( $json_value, true );
625 + $site_id = $website->id;
564 626 }
565 - return false;
566 - }
567 627
568 - /**
569 - * Get child sites by user ID.
570 - *
571 - * @param int $userid User ID.
572 - * @param bool $selectgroups Selected groups.
573 - * @param null $search_site Site search field value.
574 - * @param string $orderBy Order list by. Default: URL.
575 - *
576 - * @return array|object|null Database query results or null on failer.
577 - */
578 - public function get_websites_by_user_id( $userid, $selectgroups = false, $search_site = null, $orderBy = 'wp.url' ) {
579 - return $this->get_results_result( $this->get_sql_websites_by_user_id( $userid, $selectgroups, $search_site, $orderBy ) );
580 - }
628 + return $this->wpdb->get_var( 'SELECT value FROM ' . $this->tableName( 'wp_options' ) . ' WHERE wpid = ' . $site_id . ' AND name = "' . $this->escape( $option ) . '"' );
629 + }
581 630
582 - /**
583 - * Get child sites.
584 - *
585 - * @return string SQL string.
586 - */
587 - public function get_sql_websites() {
588 - $where = $this->get_sql_where_allow_access_sites( 'wp' );
631 + public function updateWebsiteOption( $website, $option, $value ) {
632 + $rslt = $this->wpdb->get_results( 'SELECT name FROM ' . $this->tableName( 'wp_options' ) . ' WHERE wpid = ' . $website->id . ' AND name = "' . $this->escape( $option ) . '"' );
633 + if ( count( $rslt ) > 0 ) {
634 + $this->wpdb->delete( $this->tableName( 'wp_options' ), array(
635 + 'wpid' => $website->id,
636 + 'name' => $this->escape( $option ),
637 + ) );
638 + $rslt = $this->wpdb->get_results( 'SELECT name FROM ' . $this->tableName( 'wp_options' ) . ' WHERE wpid = ' . $website->id . ' AND name = "' . $this->escape( $option ) . '"' );
639 + }
589 640
590 - return 'SELECT wp.*,wp_sync.*,wp_optionview.*
591 - FROM ' . $this->table_name( 'wp' ) . ' wp
592 - JOIN ' . $this->table_name( 'wp_sync' ) . ' wp_sync ON wp.id = wp_sync.wpid
593 - JOIN ' . $this->get_option_view() . ' wp_optionview ON wp.id = wp_optionview.wpid
594 - WHERE 1 ' . $where;
595 - }
641 + if ( count( $rslt ) == 0 ) {
642 + $this->wpdb->insert( $this->tableName( 'wp_options' ), array(
643 + 'wpid' => $website->id,
644 + 'name' => $option,
645 + 'value' => $value,
646 + ) );
647 + } else {
648 + $this->wpdb->update( $this->tableName( 'wp_options' ), array( 'value' => $value ), array(
649 + 'wpid' => $website->id,
650 + 'name' => $option,
651 + ) );
652 + }
653 + }
596 654
597 - /**
598 - * Get child sites to run the status check process.
599 - *
600 - * @param int $last_check Time of the last check.
601 - * @param int $count Number of websites.
602 - *
603 - * @return string SQL string.
604 - */
605 - public function get_sql_websites_to_check_status( $last_check, $count = 20 ) {
606 - $where = $this->get_sql_where_allow_access_sites( 'wp' );
607 - return 'SELECT wp.*
608 - FROM ' . $this->table_name( 'wp' ) . ' wp
609 - WHERE wp.disable_status_check <> 1 AND ( wp.status_check_interval = 0 AND wp.offline_checks_last < ' . intval( $last_check ) . ' )' .
610 - $where . '
611 - LIMIT ' . intval( $count );
612 - }
655 + public function getWebsitesByUserId( $userid, $selectgroups = false, $search_site = null, $orderBy = 'wp.url' ) {
656 + return $this->getResultsResult( $this->getSQLWebsitesByUserId( $userid, $selectgroups, $search_site, $orderBy ) );
657 + }
613 658
659 + public function getSQLWebsites() {
660 + $where = $this->getWhereAllowAccessSites( 'wp' );
614 661
615 - /**
616 - * Get child sites to run the status individual check process.
617 - *
618 - * @param int $count Number of websites.
619 - *
620 - * @return string SQL string.
621 - */
622 - public function get_sql_websites_to_check_individual_status( $count = 20 ) {
623 - $where = $this->get_sql_where_allow_access_sites( 'wp' );
624 - return 'SELECT wp.*
625 - FROM ' . $this->table_name( 'wp' ) . ' wp
626 - WHERE wp.disable_status_check <> 1 AND ( wp.status_check_interval <> 0 AND ( wp.offline_checks_last + wp.status_check_interval * 60 < UNIX_TIMESTAMP() ) )' .
627 - $where . '
628 - LIMIT ' . intval( $count );
629 - }
662 + return 'SELECT wp.*,wp_sync.*,wp_optionview.*
663 + FROM ' . $this->tableName( 'wp' ) . ' wp
664 + JOIN ' . $this->tableName( 'wp_sync' ) . ' wp_sync ON wp.id = wp_sync.wpid
665 + JOIN ' . $this->getOptionView() . ' wp_optionview ON wp.id = wp_optionview.wpid
666 + ' . $where;
667 + }
630 668
631 - /**
632 - * Get child sites by user id via SQL.
633 - *
634 - * @param int $userid Given user ID.
635 - * @param bool $selectgroups Selected groups. Default: false.
636 - * @param null $search_site Site search field value. Default: null.
637 - * @param string $orderBy Order list by. Default: URL.
638 - * @param bool $offset Query offset. Default: false.
639 - * @param bool $rowcount Row count. Default: falese.
640 - *
641 - * @return object|null Return database query or null on failure.
642 - *
643 - * @uses \MainWP\Dashboard\MainWP_Utility::ctype_digit()
644 - */
645 - public function get_sql_websites_by_user_id( $userid, $selectgroups = false, $search_site = null, $orderBy = 'wp.url', $offset = false, $rowcount = false ) {
646 - if ( MainWP_Utility::ctype_digit( $userid ) ) {
647 - $where = '';
648 - if ( null !== $search_site ) {
649 - $search_site = trim( $search_site );
650 - $where = ' AND (wp.name LIKE "%' . $search_site . '%" OR wp.url LIKE "%' . $search_site . '%") ';
651 - }
669 + public function getSQLWebsitesByUserId( $userid, $selectgroups = false, $search_site = null, $orderBy = 'wp.url',
670 + $offset = false, $rowcount = false ) {
671 + if ( MainWP_Utility::ctype_digit( $userid ) ) {
672 + $where = '';
673 + if ( $search_site !== null ) {
674 + $search_site = trim( $search_site );
675 + $where = ' AND (wp.name LIKE "%' . $search_site . '%" OR wp.url LIKE "%' . $search_site . '%") ';
676 + }
652 677
653 - $where .= $this->get_sql_where_allow_access_sites( 'wp' );
678 + $where .= $this->getWhereAllowAccessSites( 'wp' );
654 679
655 - if ( $selectgroups ) {
656 - $qry = 'SELECT wp.*,wp_sync.*,wp_optionview.*, GROUP_CONCAT(gr.name ORDER BY gr.name SEPARATOR ",") as wpgroups, GROUP_CONCAT(gr.id ORDER BY gr.name SEPARATOR ",") as wpgroupids, GROUP_CONCAT(gr.color ORDER BY gr.name SEPARATOR ",") as wpgroups_colors
657 - FROM ' . $this->table_name( 'wp' ) . ' wp
658 - LEFT JOIN ' . $this->table_name( 'wp_group' ) . ' wpgr ON wp.id = wpgr.wpid
659 - LEFT JOIN ' . $this->table_name( 'group' ) . ' gr ON wpgr.groupid = gr.id
660 - JOIN ' . $this->table_name( 'wp_sync' ) . ' wp_sync ON wp.id = wp_sync.wpid
661 - JOIN ' . $this->get_option_view() . ' wp_optionview ON wp.id = wp_optionview.wpid
680 + if ( $selectgroups ) {
681 + $qry = 'SELECT wp.*,wp_sync.*,wp_optionview.*, GROUP_CONCAT(gr.name ORDER BY gr.name SEPARATOR ", ") as wpgroups
682 + FROM ' . $this->tableName( 'wp' ) . ' wp
683 + LEFT JOIN ' . $this->tableName( 'wp_group' ) . ' wpgr ON wp.id = wpgr.wpid
684 + LEFT JOIN ' . $this->tableName( 'group' ) . ' gr ON wpgr.groupid = gr.id
685 + JOIN ' . $this->tableName( 'wp_sync' ) . ' wp_sync ON wp.id = wp_sync.wpid
686 + JOIN ' . $this->getOptionView() . ' wp_optionview ON wp.id = wp_optionview.wpid
662 687 WHERE wp.userid = ' . $userid . "
663 688 $where
664 - GROUP BY wp.id, wp_sync.sync_id
689 + GROUP BY wp.id
665 690 ORDER BY " . $orderBy;
666 - } else {
667 - $qry = 'SELECT wp.*,wp_sync.*,wp_optionview.*
668 - FROM ' . $this->table_name( 'wp' ) . ' wp
669 - JOIN ' . $this->table_name( 'wp_sync' ) . ' wp_sync ON wp.id = wp_sync.wpid
670 - JOIN ' . $this->get_option_view() . ' wp_optionview ON wp.id = wp_optionview.wpid
691 + } else {
692 + $qry = 'SELECT wp.*,wp_sync.*,wp_optionview.*
693 + FROM ' . $this->tableName( 'wp' ) . ' wp
694 + JOIN ' . $this->tableName( 'wp_sync' ) . ' wp_sync ON wp.id = wp_sync.wpid
695 + JOIN ' . $this->getOptionView() . ' wp_optionview ON wp.id = wp_optionview.wpid
671 696 WHERE wp.userid = ' . $userid . "
672 697 $where
673 698 ORDER BY " . $orderBy;
674 - }
699 + }
675 700
676 - if ( ( false !== $offset ) && ( false !== $rowcount ) ) {
677 - $qry .= ' LIMIT ' . $offset . ', ' . $rowcount;
678 - } elseif ( false !== $rowcount ) {
679 - $qry .= ' LIMIT ' . $rowcount;
680 - }
701 + if ( ( $offset !== false ) && ( $rowcount !== false ) ) {
702 + $qry .= ' LIMIT ' . $offset . ', ' . $rowcount;
703 + }
681 704
682 - return $qry;
683 - }
705 + return $qry;
706 + }
684 707
685 - return null;
686 - }
708 + return null;
709 + }
687 710
688 - /**
689 - * Get SQL to get child sites for current user.
690 - *
691 - * @param bool $selectgroups Selected groups. Default: false.
692 - * @param null $search_site Site search field value. Default: null.
693 - * @param string $orderBy Order list by. Default: URL.
694 - * @param bool $offset Query offset. Default: false.
695 - * @param bool $rowcount Row count. Default: false.
696 - * @param null $extraWhere Extra WHERE. Default: null.
697 - * @param bool $for_manager For role manager. Default: false.
698 - * @param mixed $extra_view Extra view. Default favi_icon.
699 - * @param string $is_staging yes|no Is child site a staging site.
700 - * @param array $params other params.
701 - *
702 - * @return object|null Database query results or null on failure.
703 - *
704 - * @uses \MainWP\Dashboard\MainWP_System::is_multi_user()
705 - */
706 - public function get_sql_websites_for_current_user( // phpcs:ignore -- NOSONAR - complex.
707 - $selectgroups = false,
708 - $search_site = null,
709 - $orderBy = 'wp.url',
710 - $offset = false,
711 - $rowcount = false,
712 - $extraWhere = null,
713 - $for_manager = false,
714 - $extra_view = array( 'favi_icon' ),
715 - $is_staging = 'no',
716 - $params = array()
717 - ) {
711 + public function getSQLWebsitesForCurrentUser( $selectgroups = false, $search_site = null, $orderBy = 'wp.url',
712 + $offset = false, $rowcount = false, $extraWhere = null, $for_manager = false,
713 + $extra_view = array( 'favi_icon' ), $is_staging = 'no' ) {
714 + $where = '';
715 + if ( MainWP_System::Instance()->isMultiUser() ) {
716 + global $current_user;
717 + $where .= ' AND wp.userid = ' . $current_user->ID . ' ';
718 + }
718 719
719 - $where = '';
720 - if ( MainWP_System::instance()->is_multi_user() ) {
720 + if ( $search_site !== null ) {
721 + $search_site = trim( $search_site );
722 + $where .= ' AND (wp.name LIKE "%' . $search_site . '%" OR wp.url LIKE "%' . $search_site . '%") ';
723 + }
721 724
722 - /**
723 - * Current user global.
724 - *
725 - * @global string
726 - */
727 - global $current_user;
725 + if ( $extraWhere !== null ) {
726 + $where .= ' AND ' . $extraWhere;
727 + }
728 728
729 - $where .= ' AND wp.userid = ' . $current_user->ID . ' ';
730 - }
729 + if ( !$for_manager ) {
730 + $where .= $this->getWhereAllowAccessSites( 'wp', $is_staging );
731 + }
731 732
732 - if ( null !== $search_site ) {
733 - $search_site = trim( $search_site );
734 - $where .= ' AND (wp.name LIKE "%' . $search_site . '%" OR wp.url LIKE "%' . $search_site . '%") ';
735 - }
733 + if ( $orderBy == 'wp.url' ) {
734 + $orderBy = "replace(replace(replace(replace(replace(wp.url, 'https://www.',''), 'http://www.',''), 'https://', ''), 'http://', ''), 'www', '')";
735 + }
736 736
737 - if ( null !== $extraWhere ) {
738 - $where .= ' AND ' . $extraWhere;
739 - }
737 + // wpgroups to fix issue for mysql 8.0, as groups will generate error syntax
738 + if ( $selectgroups ) {
739 + $qry = 'SELECT wp.*,wp_sync.*,wp_optionview.*, GROUP_CONCAT(gr.name ORDER BY gr.name SEPARATOR ", ") as wpgroups
740 + FROM ' . $this->tableName( 'wp' ) . ' wp
741 + LEFT JOIN ' . $this->tableName( 'wp_group' ) . ' wpgr ON wp.id = wpgr.wpid
742 + LEFT JOIN ' . $this->tableName( 'group' ) . ' gr ON wpgr.groupid = gr.id
743 + JOIN ' . $this->tableName( 'wp_sync' ) . ' wp_sync ON wp.id = wp_sync.wpid
744 + JOIN ' . $this->getOptionView( $extra_view ) . ' wp_optionview ON wp.id = wp_optionview.wpid
745 + WHERE 1 ' . $where . '
746 + GROUP BY wp.id
747 + ORDER BY ' . $orderBy;
748 + } else {
749 + $qry = 'SELECT wp.*,wp_sync.*,wp_optionview.*
750 + FROM ' . $this->tableName( 'wp' ) . ' wp
751 + JOIN ' . $this->tableName( 'wp_sync' ) . ' wp_sync ON wp.id = wp_sync.wpid
752 + JOIN ' . $this->getOptionView( $extra_view ) . ' wp_optionview ON wp.id = wp_optionview.wpid
753 + WHERE 1 ' . $where . '
754 + ORDER BY ' . $orderBy;
755 + }
740 756
741 - if ( ! $for_manager ) {
742 - $where .= $this->get_sql_where_allow_access_sites( 'wp', $is_staging );
743 - }
757 + if ( ( $offset !== false ) && ( $rowcount !== false ) ) {
758 + $qry .= ' LIMIT ' . $offset . ', ' . $rowcount;
759 + }
744 760
745 - $connected_sql = '';
761 + return $qry;
762 + }
746 763
747 - if ( is_array( $params ) && isset( $params['connected'] ) && 'yes' === $params['connected'] ) {
748 - $connected_sql = ' AND wp_sync.sync_errors = "" ';
749 - } elseif ( is_array( $params ) && isset( $params['connected'] ) && 'no' === $params['connected'] ) {
750 - $connected_sql = ' AND wp_sync.sync_errors <> "" ';
751 - }
764 + public function getSQLSearchWebsitesForCurrentUser( $params ) {
752 765
753 - if ( 'wp.url' === $orderBy ) {
754 - $orderBy = "replace(replace(replace(replace(replace(wp.url, 'https://www.',''), 'http://www.',''), 'https://', ''), 'http://', ''), 'www.', '')";
755 - }
766 + if ( !is_array($params) )
767 + $params = array();
756 768
757 - // wpgroups to fix issue for mysql 8.0, as groups will generate error syntax.
758 - if ( $selectgroups ) {
759 - $qry = 'SELECT wp.*,wp_sync.*,wp_optionview.*, GROUP_CONCAT(gr.name ORDER BY gr.name SEPARATOR ",") as wpgroups, GROUP_CONCAT(gr.id ORDER BY gr.name SEPARATOR ",") as wpgroupids, GROUP_CONCAT(gr.color ORDER BY gr.name SEPARATOR ",") as wpgroups_colors,
760 - wpclient.name as client_name
761 - FROM ' . $this->table_name( 'wp' ) . ' wp
762 - LEFT JOIN ' . $this->table_name( 'wp_group' ) . ' wpgr ON wp.id = wpgr.wpid
763 - LEFT JOIN ' . $this->table_name( 'group' ) . ' gr ON wpgr.groupid = gr.id
764 - LEFT JOIN ' . $this->table_name( 'wp_clients' ) . ' wpclient ON wp.client_id = wpclient.client_id
765 - JOIN ' . $this->table_name( 'wp_sync' ) . ' wp_sync ON wp.id = wp_sync.wpid
766 - JOIN ' . $this->get_option_view( $extra_view ) . ' wp_optionview ON wp.id = wp_optionview.wpid
767 - WHERE 1 ' . $where . $connected_sql . '
768 - GROUP BY wp.id, wp_sync.sync_id
769 + $selectgroups = isset($params['selectgroups']) && $params['selectgroups'] ? true : false;
770 + $search_site = isset($params['search']) ? $this->escape(trim($params['search'])) : null;
771 + $orderBy = isset($params['orderby']) ? $params['orderby'] : 'wp.url';
772 + $offset = isset($params['offset']) ? intval($params['offset']) : false;
773 + $rowcount = isset($params['rowcount']) ? intval($params['rowcount']) : false;
774 + $extraWhere = isset($params['extra_where']) ? $params['extra_where'] : null;
775 + $for_manager = isset($params['for_manager']) && $params['for_manager'] ? true : false;
776 + $extra_view = isset($params['extra_view']) ? $params['extra_view'] : array( 'favi_icon' ) ;
777 + $is_staging = isset($params['is_staging']) && $params['is_staging'] == 'yes' ? 'yes' : 'no' ;
778 +
779 + $group_id = isset($params['group_id']) && $params['group_id'] ? intval($params['group_id']) : false;
780 +
781 + if ( $selectgroups ) {
782 + if ( $staging_group = get_option( 'mainwp_stagingsites_group_id' ) ) {
783 + if ( $group_id == $staging_group ) {
784 + $is_staging = 'yes'; // will list staging sites
785 + }
786 + }
787 + }
788 +
789 + $where = '';
790 + if ( MainWP_System::Instance()->isMultiUser() ) {
791 + global $current_user;
792 + $where .= ' AND wp.userid = ' . $current_user->ID . ' ';
793 + }
794 +
795 + // for searching
796 + if ( $search_site !== null && $search_site != '' ) {
797 + $where .= ' AND (wp.name LIKE "%' . $search_site . '%" OR wp.url LIKE "%' . $search_site . '%") ';
798 + }
799 +
800 + if ( $extraWhere !== null ) {
801 + $where .= ' AND ' . $extraWhere;
802 + }
803 +
804 + if ( ! $for_manager ) {
805 + $where .= $this->getWhereAllowAccessSites( 'wp', $is_staging );
806 + }
807 +
808 + if ( $orderBy == 'wp.url' ) {
809 + $orderBy = "replace(replace(replace(replace(replace(wp.url, 'https://www.',''), 'http://www.',''), 'https://', ''), 'http://', ''), 'www', '')";
810 + }
811 +
812 + $join_group = "";
813 + $where_group = "";
814 +
815 + if ( MainWP_Utility::ctype_digit( $group_id ) && $group_id > 0 ) {
816 + $join_group = " JOIN " . $this->tableName( 'wp_group' ) . " wpgroup ON wp.id = wpgroup.wpid ";
817 + $where_group = " AND wpgroup.groupid = " . $group_id;
818 + }
819 +
820 + // wpgroups to fix issue for mysql 8.0, as groups will generate error syntax
821 + if ( $selectgroups ) {
822 + $qry = 'SELECT wp.*,wp_sync.*,wp_optionview.*, GROUP_CONCAT(gr.name ORDER BY gr.name SEPARATOR ", ") as wpgroups
823 + FROM ' . $this->tableName( 'wp' ) . ' wp ' .
824 + $join_group . '
825 + LEFT JOIN ' . $this->tableName( 'wp_group' ) . ' wpgr ON wp.id = wpgr.wpid
826 + LEFT JOIN ' . $this->tableName( 'group' ) . ' gr ON wpgr.groupid = gr.id
827 + JOIN ' . $this->tableName( 'wp_sync' ) . ' wp_sync ON wp.id = wp_sync.wpid
828 + JOIN ' . $this->getOptionView( $extra_view ) . ' wp_optionview ON wp.id = wp_optionview.wpid
829 + WHERE 1 ' . $where . $where_group . '
830 + GROUP BY wp.id
769 831 ORDER BY ' . $orderBy;
770 - } else {
771 - $qry = 'SELECT wp.*,wp_sync.*,wp_optionview.*, wpclient.name as client_name
772 - FROM ' . $this->table_name( 'wp' ) . ' wp
773 - LEFT JOIN ' . $this->table_name( 'wp_clients' ) . ' wpclient ON wp.client_id = wpclient.client_id
774 - JOIN ' . $this->table_name( 'wp_sync' ) . ' wp_sync ON wp.id = wp_sync.wpid
775 - JOIN ' . $this->get_option_view( $extra_view ) . ' wp_optionview ON wp.id = wp_optionview.wpid
776 - WHERE 1 ' . $where . $connected_sql . '
777 - GROUP BY wp.id, wp_sync.sync_id
832 + } else {
833 + $qry = 'SELECT wp.*,wp_sync.*,wp_optionview.*
834 + FROM ' . $this->tableName( 'wp' ) . ' wp ' .
835 + $join_group . '
836 + JOIN ' . $this->tableName( 'wp_sync' ) . ' wp_sync ON wp.id = wp_sync.wpid
837 + JOIN ' . $this->getOptionView( $extra_view ) . ' wp_optionview ON wp.id = wp_optionview.wpid
838 + WHERE 1 ' . $where . $where_group . '
778 839 ORDER BY ' . $orderBy;
779 - }
840 + }
780 841
781 - if ( ( false !== $offset ) && ( false !== $rowcount ) ) {
782 - $qry .= ' LIMIT ' . $offset . ', ' . $rowcount;
783 - } elseif ( false !== $rowcount ) {
784 - $qry .= ' LIMIT ' . $rowcount;
785 - }
842 + if ( ( $offset !== false ) && ( $rowcount !== false ) ) {
843 + $qry .= ' LIMIT ' . $offset . ', ' . $rowcount;
844 + }
786 845
787 - return $qry;
788 - }
846 + return $qry;
847 + }
789 848
790 - /**
791 - * Get SQL to get wp child sites for current user.
792 - *
793 - * @since 4.3
794 - *
795 - * @param array $params params .
796 - *
797 - * @return object|null Database query results or null on failure.
798 - */
799 - public function get_sql_wp_for_current_user( $params = array() ) { // phpcs:ignore -- NOSONAR - complex.
800 - if ( ! is_array( $params ) ) {
801 - $params = array();
802 - }
803 849
804 - $selectgroups = ! empty( $params['select_groups'] ) ? true : false;
805 - $search_site = isset( $params['search_site'] ) && ! empty( $params['search_site'] ) ? $params['search_site'] : null;
806 - $orderBy = isset( $params['order_by'] ) && ! empty( $params['order_by'] ) ? $params['order_by'] : 'wp.url';
807 - $offset = isset( $params['offset'] ) ? $params['offset'] : false;
808 - $rowcount = isset( $params['row_count'] ) ? $params['row_count'] : false;
809 - $for_manager = isset( $params['for_manager'] ) ? $params['for_manager'] : false;
810 - $extraWhere = isset( $params['extra_where'] ) && ! empty( $params['extra_where'] ) ? $params['extra_where'] : null;
811 - $extra_view = isset( $params['extra_view'] ) && is_array( $params['extra_view'] ) && ! empty( $params['extra_view'] ) ? $params['extra_view'] : array( 'favi_icon' );
812 - $extra_join = isset( $params['extra_join'] ) ? $params['extra_join'] : '';
850 + public function getWhereAllowAccessSites( $site_table_alias = '', $is_staging = 'no' ) {
813 851
814 - $extra_select_wp_fields = isset( $params['extra_select_wp_fields'] ) && is_array( $params['extra_select_wp_fields'] ) && ! empty( $params['extra_select_wp_fields'] ) ? $params['extra_select_wp_fields'] : array();
815 - $extra_select_sql_fields = isset( $params['extra_select_sql_fields'] ) && ! empty( $params['extra_select_sql_fields'] ) ? $params['extra_select_sql_fields'] : '';
852 + if ( empty( $site_table_alias ) ) {
853 + $site_table_alias = $this->tableName( 'wp' );
854 + }
816 855
817 - $is_staging = isset( $params['is_staging'] ) && 'yes' === $params['is_staging'] ? 'yes' : 'no';
818 - $count_only = isset( $params['count_only'] ) && $params['count_only'] ? true : false;
856 + // check to filter the staging sites
857 + $where_staging = ' AND ' . $site_table_alias . '.is_staging = 0 ';
858 + if ( $is_staging == 'no' ) {
859 + $where_staging = ' AND ' . $site_table_alias . '.is_staging = 0 ';
860 + } else if ( $is_staging == 'yes' ) {
861 + $where_staging = ' AND ' . $site_table_alias . '.is_staging = 1 ';
862 + } else if ( $is_staging == 'nocheckstaging' ) {
863 + $where_staging = '';
864 + }
865 + // end staging filter
819 866
820 - $where = '';
867 + $_where = $where_staging;
868 + // To fix bug run from cron job
869 + if ( defined( 'DOING_CRON' ) && DOING_CRON ) {
870 + return $_where;
871 + }
821 872
822 - if ( null !== $search_site ) {
823 - $search_site = trim( $search_site );
824 - $where .= ' AND (wp.name LIKE "%' . $this->escape( $search_site ) . '%" OR wp.url LIKE "%' . $this->escape( $search_site ) . '%") ';
825 - }
873 + // To fix bug run from wp cli
874 + if ( defined( 'WP_CLI' ) && WP_CLI ) {
875 + return $_where;
876 + }
826 877
827 - if ( null !== $extraWhere ) {
828 - $where .= ' AND ' . $extraWhere;
829 - }
878 + $allowed_sites = apply_filters( 'mainwp_currentuserallowedaccesssites', 'all' );
830 879
831 - if ( ! $for_manager ) {
832 - $where .= $this->get_sql_where_allow_access_sites( 'wp', $is_staging );
833 - }
880 + if ( $allowed_sites == 'all' ) {
881 + return $_where; // allow access all sites
882 + }
834 883
835 - if ( 'wp.url' === $orderBy ) {
836 - $orderBy = "replace(replace(replace(replace(replace(wp.url, 'https://www.',''), 'http://www.',''), 'https://', ''), 'http://', ''), 'www.', '')";
837 - }
838 884
839 - $select_wp_fields = $this->get_sql_select_wp_valid_fields( $extra_select_wp_fields );
885 + if ( is_array( $allowed_sites ) && count( $allowed_sites ) > 0 ) {
886 + $_where .= ' AND ' . $site_table_alias . '.id IN (' . implode( ',', $allowed_sites ) . ') ';
887 + } else {
888 + $_where .= ' AND 0 '; // denied access
889 + }
840 890
841 - if ( ! empty( $extra_select_sql_fields ) ) {
842 - $extra_select_sql_fields = ',' . $extra_select_sql_fields;
843 - }
891 + return $_where;
892 + }
844 893
845 - // wpgroups to fix issue for mysql 8.0, as groups will generate error syntax.
846 - if ( $selectgroups ) {
847 - if ( $count_only ) {
848 - $select = ' COUNT(DISTINCT(wp.id)) ';
849 - } else {
850 - $select = $select_wp_fields . '
851 - ' . $extra_select_sql_fields . '
852 - ,wp_sync.sync_errors,wp_optionview.*, GROUP_CONCAT(gr.name ORDER BY gr.name SEPARATOR ",") as wpgroups, GROUP_CONCAT(gr.id ORDER BY gr.name SEPARATOR ",") as wpgroupids, GROUP_CONCAT(gr.color ORDER BY gr.name SEPARATOR ",") as wpgroups_colors, wpclient.name as client_name ';
853 - }
854 - $qry = 'SELECT ' . $select . '
855 - FROM ' . $this->table_name( 'wp' ) . ' wp
856 - LEFT JOIN ' . $this->table_name( 'wp_group' ) . ' wpgr ON wp.id = wpgr.wpid
857 - LEFT JOIN ' . $this->table_name( 'group' ) . ' gr ON wpgr.groupid = gr.id
858 - LEFT JOIN ' . $this->table_name( 'wp_clients' ) . ' wpclient ON wp.client_id = wpclient.client_id
859 - JOIN ' . $this->table_name( 'wp_sync' ) . ' wp_sync ON wp.id = wp_sync.wpid
860 - JOIN ' . $this->get_option_view( $extra_view ) . ' wp_optionview ON wp.id = wp_optionview.wpid ' .
861 - $extra_join . '
862 - WHERE 1 ' . $where;
863 - if ( ! $count_only ) {
864 - $qry .= ' GROUP BY wp.id, wp_sync.sync_id';
865 - }
866 - $qry .= ' ORDER BY ' . $orderBy;
867 - } else {
868 - if ( $count_only ) {
869 - $select = ' COUNT(DISTINCT(wp.id)) ';
870 - } else {
871 - $select = $select_wp_fields . '
872 - ' . $extra_select_sql_fields . '
873 - ,wp_sync.sync_errors,wp_optionview.*, wpclient.name as client_name ';
874 - }
875 - $qry = 'SELECT ' . $select . '
876 - FROM ' . $this->table_name( 'wp' ) . ' wp
877 - LEFT JOIN ' . $this->table_name( 'wp_clients' ) . ' wpclient ON wp.client_id = wpclient.client_id
878 - JOIN ' . $this->table_name( 'wp_sync' ) . ' wp_sync ON wp.id = wp_sync.wpid
879 - JOIN ' . $this->get_option_view( $extra_view ) . ' wp_optionview ON wp.id = wp_optionview.wpid ' .
880 - $extra_join . '
881 - WHERE 1 ' . $where;
882 - if ( ! $count_only ) {
883 - $qry .= ' GROUP BY wp.id, wp_sync.sync_id';
884 - }
885 - $qry .= ' ORDER BY ' . $orderBy;
886 - }
894 + public function getWhereAllowGroups( $group_table_alias = '', $with_staging = 'no' ) {
895 + // To fix bug run from cron job
896 + if ( defined( 'DOING_CRON' ) && DOING_CRON ) {
897 + return '';
898 + }
887 899
888 - if ( ! $count_only ) {
889 - if ( ( false !== $offset ) && ( false !== $rowcount ) ) {
890 - $qry .= ' LIMIT ' . intval( $offset ) . ', ' . intval( $rowcount );
891 - } elseif ( false !== $rowcount ) {
892 - $qry .= ' LIMIT ' . intval( $rowcount );
893 - }
894 - }
895 - return $qry;
896 - }
897 - /**
898 - * Get SQL select websites fields.
899 - *
900 - * @since 4.3
901 - *
902 - * @param array $other_fields extra select wp fields .
903 - *
904 - * @return string sql string.
905 - */
906 - public function get_sql_select_wp_valid_fields( $other_fields = array() ) {
900 + if ( empty( $group_table_alias ) ) {
901 + $group_table_alias = $this->tableName( 'group' );
902 + }
907 903
908 - $allow_other_fields = array(
909 - 'offline_checks_last',
910 - 'offline_check_result',
911 - 'http_response_code',
912 - 'disable_status_check',
913 - 'disable_health_check',
914 - 'status_check_interval',
915 - 'health_threshold',
916 - 'note',
917 - 'statsUpdate',
918 - 'directories',
919 - 'plugin_upgrades',
920 - 'theme_upgrades',
921 - 'translation_upgrades',
922 - 'premium_upgrades',
923 - 'securityIssues',
924 - 'themes',
925 - 'ignored_themes',
926 - 'plugins',
927 - 'ignored_plugins',
928 - 'users',
929 - 'categories',
930 - 'pluginDir',
931 - 'automatic_update',
932 - 'backup_before_upgrade',
933 - 'mainwpdir',
934 - 'is_ignoreCoreUpdates',
935 - 'is_ignorePluginUpdates',
936 - 'is_ignoreThemeUpdates',
937 - 'verify_certificate',
938 - 'force_use_ipv4',
939 - 'ssl_version',
940 - 'http_user',
941 - 'http_pass',
942 - 'wpe',
943 - 'is_staging',
944 - 'client_id',
945 - );
904 + // check to filter the staging group
905 + $where_staging_group = '';
906 + $staging_group = get_option( 'mainwp_stagingsites_group_id' );
907 + if ( $staging_group ) {
908 + $where_staging_group = ' AND ' . $group_table_alias . '.id <> ' . $staging_group . ' '; // filter the staging group
909 + if ( $with_staging == 'yes' ) {
910 + $where_staging_group = ''; // will do not the filter staging group
911 + }
912 + }
913 + // end staging filter
946 914
947 - $default_fields = array( 'id', 'url', 'name', 'adminname', 'verify_certificate', 'ssl_version', 'http_user', 'http_pass', 'suspended' );
915 + $_where = $where_staging_group;
948 916
949 - $select = ' ';
917 + $allowed_groups = apply_filters( 'mainwp_currentuserallowedaccessgroups', 'all' );
950 918
951 - foreach ( $default_fields as $field ) {
952 - $select .= 'wp.' . $this->escape( $field ) . ',';
953 - }
954 - foreach ( $other_fields as $field ) {
955 - if ( ! in_array( $field, $allow_other_fields ) ) {
956 - continue;
957 - }
958 - if ( in_array( $field, $default_fields ) ) {
959 - continue;
960 - }
961 - $select .= 'wp.' . $this->escape( $field ) . ',';
962 - }
963 - $select = rtrim( $select, ',' );
964 - return $select;
965 - }
919 + if ( $allowed_groups == 'all' ) {
920 + return $_where;
921 + } // allow all groups
966 922
967 - /**
968 - * Get child sites for current user.
969 - *
970 - * @param array $params to get sites. Default: array().
971 - *
972 - * @return array Results or null on failure.
973 - *
974 - * @uses \MainWP\Dashboard\MainWP_Utility::map_site()
975 - */
976 - public function get_websites_for_current_user( $params = array() ) { // phpcs:ignore -- NOSONAR - complex.
977 - if ( ! is_array( $params ) ) {
978 - $params = array();
979 - }
980 923
981 - $selectgroups = isset( $params['selectgroups'] ) ? $params['selectgroups'] : false;
982 - $search_site = isset( $params['search_site'] ) ? $params['search_site'] : null;
983 - $orderBy = isset( $params['order_by'] ) ? $params['order_by'] : 'wp.url';
984 - $offset = isset( $params['offset'] ) ? $params['offset'] : false;
985 - $rowcount = isset( $params['rowcount'] ) ? $params['rowcount'] : false;
986 - $extraWhere = isset( $params['where'] ) ? $params['where'] : null;
987 - $extra_view = isset( $params['extra_view'] ) && is_array( $params['extra_view'] ) ? $params['extra_view'] : array( 'favi_icon' );
988 - $is_staging = isset( $params['is_staging'] ) ? $params['is_staging'] : 'no';
989 - $full_data = isset( $params['full_data'] ) && $params['full_data'] && ( 'no' !== $params['full_data'] ) ? true : false;
990 - $select_data = isset( $params['select_data'] ) && is_array( $params['select_data'] ) ? $params['select_data'] : false;
991 - $format = isset( $params['format'] ) ? $params['format'] : '';
992 - $clients = isset( $params['client'] ) ? $params['client'] : '';
924 + if ( is_array( $allowed_groups ) && count( $allowed_groups ) > 0 ) {
925 + return ' AND ' . $group_table_alias . '.id IN (' . implode( ',', $allowed_groups ) . ') ' . $_where;
926 + } else {
927 + return ' AND 0 '; // not allow access groups
928 + }
929 + }
993 930
994 - $for_manager = false;
931 + public function getGroupByNameForUser( $name, $userid = null ) {
932 + if ( ( $userid == null ) && MainWP_System::Instance()->isMultiUser() ) {
933 + global $current_user;
934 + $userid = $current_user->ID;
935 + }
936 + $where = ( $userid != null ) ? ' AND userid=' . $userid : '';
937 + $where .= $this->getWhereAllowGroups();
995 938
996 - $urlsWhere = '';
939 + return $this->wpdb->get_row( 'SELECT * FROM ' . $this->tableName( 'group' ) . ' WHERE 1 ' . $where . ' AND name="' . $this->escape( $name ) . '"' );
940 + }
997 941
998 - if ( isset( $params['urls'] ) && ! empty( $params['urls'] ) ) {
999 - $urls = explode( ';', $params['urls'] );
1000 - foreach ( $urls as $url ) {
1001 - $url = str_replace( array( 'https://www.', 'http://www.', 'https://', 'http://', 'www.' ), array( '', '', '', '', '' ), $url );
1002 - if ( '/' !== substr( $url, - 1 ) ) {
1003 - $url .= '/';
1004 - }
1005 - $urlsWhere .= '"' . $this->escape( $url ) . '", ';
1006 - }
1007 - $urlsWhere = rtrim( $urlsWhere, ', ' );
1008 - }
942 + public function getGroupById( $id ) {
943 + if ( MainWP_Utility::ctype_digit( $id ) ) {
944 + return $this->wpdb->get_row( 'SELECT * FROM ' . $this->tableName( 'group' ) . ' WHERE id=' . $id );
945 + }
1009 946
1010 - if ( ! empty( $urlsWhere ) ) {
1011 - $urlsWhere = " ( replace(replace(replace(replace(replace(wp.url, 'https://www.',''), 'http://www.',''), 'https://', ''), 'http://', ''), 'www.', '') IN ( " . $urlsWhere . ') ) ';
947 + return null;
948 + }
1012 949
1013 - if ( empty( $extraWhere ) ) {
1014 - $extraWhere = $urlsWhere;
1015 - } else {
1016 - $extraWhere = $extraWhere . ' AND ' . $urlsWhere;
1017 - }
1018 - }
950 + public function getGroupsByUserId( $userid ) {
951 + if ( MainWP_Utility::ctype_digit( $userid ) ) {
952 + $where = $this->getWhereAllowGroups();
1019 953
1020 - $clientWhere = '';
1021 - if ( ! empty( $clients ) ) {
1022 - $clients = explode( ';', $clients );
1023 - foreach ( $clients as $client ) {
1024 - if ( is_numeric( $client ) ) {
1025 - $clientWhere .= intval( $client ) . ', ';
1026 - }
1027 - }
1028 - $clientWhere = rtrim( $clientWhere, ', ' );
1029 - }
954 + return $this->wpdb->get_results( 'SELECT * FROM ' . $this->tableName( 'group' ) . ' WHERE userid = ' . $userid . $where . ' ORDER BY name', OBJECT_K );
955 + }
1030 956
1031 - if ( ! empty( $clientWhere ) ) {
1032 - $clientWhere = ' ( wp.client_id IN ( ' . $clientWhere . ') ) ';
1033 - if ( empty( $extraWhere ) ) {
1034 - $extraWhere = $clientWhere;
1035 - } else {
1036 - $extraWhere = $extraWhere . ' AND ' . $clientWhere;
1037 - }
1038 - }
957 + return null;
958 + }
1039 959
1040 - $data = array( 'id', 'url', 'name', 'client_id' );
960 + public function getGroupsForManageSites() {
961 + $where = ' 1 ';
962 + if ( MainWP_System::Instance()->isMultiUser() ) {
963 + global $current_user;
964 + $where = ' userid = ' . $current_user->ID . ' ';
965 + }
966 + $with_staging = 'yes';
967 + $staging_enabled = apply_filters('mainwp-extension-available-check', 'mainwp-staging-extension') || apply_filters('mainwp-extension-available-check', 'mainwp-timecapsule-extension');
1041 968
1042 - if ( $full_data ) {
1043 - $data = array(
1044 - 'id',
1045 - 'url',
1046 - 'name',
1047 - 'offline_checks_last',
1048 - 'offline_check_result',
1049 - 'http_response_code',
1050 - 'disable_status_check',
1051 - 'disable_health_check',
1052 - 'status_check_interval',
1053 - 'health_threshold',
1054 - 'note',
1055 - 'plugin_upgrades',
1056 - 'theme_upgrades',
1057 - 'translation_upgrades',
1058 - 'securityIssues',
1059 - 'themes',
1060 - 'plugins',
1061 - 'automatic_update',
1062 - 'sync_errors',
1063 - 'dtsAutomaticSync',
1064 - 'dtsAutomaticSyncStart',
1065 - 'dtsSync',
1066 - 'dtsSyncStart',
1067 - 'last_post_gmt',
1068 - 'health_value',
1069 - 'phpversion',
1070 - 'wp_upgrades',
1071 - 'security_stats',
1072 - 'client_id',
1073 - 'adminname',
1074 - 'privkey',
1075 - 'http_user',
1076 - 'http_pass',
1077 - 'ssl_version',
1078 - 'signature_algo',
1079 - 'verify_method',
1080 - 'verify_certificate',
1081 - );
969 + if ( !$staging_enabled ) {
970 + $with_staging = 'no';
971 + }
1082 972
1083 - if ( ! in_array( 'security_stats', $extra_view ) ) {
1084 - $extra_view[] = 'security_stats';
1085 - }
1086 - }
973 + $where .= $this->getWhereAllowGroups('' , $with_staging );
974 + return $this->wpdb->get_results( 'SELECT * FROM ' . $this->tableName( 'group' ) . ' WHERE ' . $where . ' ORDER BY name', OBJECT_K );
975 + }
1087 976
1088 - if ( ! empty( $select_data ) && is_array( $select_data ) ) {
1089 - $data = $select_data;
1090 - }
977 + public function getGroupsForCurrentUser() {
978 + $where = ' 1 ';
979 + if ( MainWP_System::Instance()->isMultiUser() ) {
980 + global $current_user;
981 + $where = ' userid = ' . $current_user->ID . ' ';
982 + }
983 + $where .= $this->getWhereAllowGroups();
1091 984
1092 - if ( $selectgroups ) {
1093 - $data[] = 'wpgroups';
1094 - }
985 + return $this->wpdb->get_results( 'SELECT * FROM ' . $this->tableName( 'group' ) . ' WHERE ' . $where . ' ORDER BY name', OBJECT_K );
986 + }
1095 987
1096 - $dbwebsites = array();
1097 - $websites = $this->query( $this->get_sql_websites_for_current_user( $selectgroups, $search_site, $orderBy, $offset, $rowcount, $extraWhere, $for_manager, $extra_view, $is_staging ) );
1098 - while ( $websites && ( $website = static::fetch_object( $websites ) ) ) {
1099 - $obj_data = MainWP_Utility::map_site( $website, $data );
988 + public function getGroupsByWebsiteId( $websiteid ) {
989 + if ( MainWP_Utility::ctype_digit( $websiteid ) ) {
990 + return $this->wpdb->get_results( 'SELECT * FROM ' . $this->tableName( 'group' ) . ' gr
991 + JOIN ' . $this->tableName( 'wp_group' ) . ' wpgr ON gr.id = wpgr.groupid
992 + WHERE wpgr.wpid = ' . $websiteid . ' ORDER BY name', OBJECT_K );
993 + }
1100 994
1101 - if ( $full_data ) {
1102 - $sum_upgrades = 0;
1103 - if ( '' !== $obj_data->plugin_upgrades ) {
1104 - $plugin_upgrades = json_decode( $obj_data->plugin_upgrades, true );
1105 - if ( is_array( $plugin_upgrades ) ) {
1106 - $sum_upgrades += count( $plugin_upgrades );
1107 - }
1108 - }
995 + return null;
996 + }
1109 997
1110 - if ( '' !== $obj_data->theme_upgrades ) {
1111 - $theme_upgrades = json_decode( $obj_data->theme_upgrades, true );
1112 - if ( is_array( $theme_upgrades ) ) {
1113 - $sum_upgrades += count( $theme_upgrades );
1114 - }
1115 - }
998 + public function getGroupsAndCount( $userid = null, $for_manager = false ) {
999 + if ( ( $userid == null ) && MainWP_System::Instance()->isMultiUser() ) {
1000 + global $current_user;
1001 + $userid = $current_user->ID;
1002 + }
1116 1003
1117 - if ( '' !== $obj_data->wp_upgrades ) {
1118 - $wp_upgrades = json_decode( $obj_data->wp_upgrades, true );
1119 - if ( is_array( $wp_upgrades ) ) {
1120 - $sum_upgrades += count( $wp_upgrades );
1121 - }
1122 - }
1123 - $obj_data->sum_of_upgrades = $sum_upgrades;
1124 - }
1004 + $where = '';
1125 1005
1126 - if ( 'array' === $format ) {
1127 - $dbwebsites[] = $obj_data;
1128 - } else {
1129 - $dbwebsites[ $website->id ] = $obj_data;
1130 - }
1131 - }
1132 - static::free_result( $websites );
1133 - return $dbwebsites;
1134 - }
1006 + if ( $userid != null ) {
1007 + $where = ' AND gr.userid = ' . $userid;
1008 + }
1135 1009
1136 - /**
1137 - * Get the child sites the current user has searched for.
1138 - *
1139 - * @param array $params Query parameters.
1140 - *
1141 - * @return boolean|null $qry Database query results or null on failure.
1142 - *
1143 - * @uses \MainWP\Dashboard\MainWP_System::is_multi_user()
1144 - */
1145 - public function get_sql_search_websites_for_current_user( $params ) { // phpcs:ignore -- NOSONAR - complex.
1010 + if ( !$for_manager ) {
1011 + $where .= $this->getWhereAllowGroups( 'gr' );
1012 + }
1146 1013
1147 - if ( ! is_array( $params ) ) {
1148 - $params = array();
1149 - }
1014 + return $this->wpdb->get_results( 'SELECT gr.*, COUNT(DISTINCT(wpgr.wpid)) as nrsites
1015 + FROM ' . $this->tableName( 'group' ) . ' gr
1016 + LEFT JOIN ' . $this->tableName( 'wp_group' ) . ' wpgr ON gr.id = wpgr.groupid
1017 + WHERE 1 ' . $where . '
1018 + GROUP BY gr.id
1019 + ORDER BY gr.name', OBJECT_K );
1020 + }
1150 1021
1151 - $selectgroups = isset( $params['selectgroups'] ) && $params['selectgroups'] ? true : false;
1152 - $search_site = isset( $params['search'] ) ? $this->escape( trim( $params['search'] ) ) : null;
1153 - $orderBy = isset( $params['orderby'] ) ? $params['orderby'] : 'wp.url';
1154 - $offset = isset( $params['offset'] ) ? intval( $params['offset'] ) : false;
1155 - $rowcount = isset( $params['rowcount'] ) ? intval( $params['rowcount'] ) : false;
1156 - $extraWhere = isset( $params['extra_where'] ) ? $params['extra_where'] : null;
1157 - $for_manager = isset( $params['for_manager'] ) && $params['for_manager'] ? true : false;
1158 - $extra_view = isset( $params['extra_view'] ) ? $params['extra_view'] : array( 'favi_icon' );
1159 - $is_staging = isset( $params['is_staging'] ) && 'yes' === $params['is_staging'] ? 'yes' : 'no';
1160 - $is_count = isset( $params['count_only'] ) && $params['count_only'] ? true : false;
1161 - $group_ids = isset( $params['group_id'] ) && ! empty( $params['group_id'] ) ? $params['group_id'] : array();
1162 - $client_ids = isset( $params['client_id'] ) && ! empty( $params['client_id'] ) ? $params['client_id'] : array();
1163 - $is_not = isset( $params['isnot'] ) && ! empty( $params['isnot'] ) ? true : false;
1164 - $selected_sites = isset( $params['selected_sites'] ) ? $params['selected_sites'] : array();
1022 + public function getGroupsByName( $name ) {
1023 + return $this->wpdb->get_results( 'SELECT gr.*
1024 + FROM ' . $this->tableName( 'group' ) . ' gr
1025 + WHERE gr.name = "' . $this->escape( $name ) . '"'
1026 + , OBJECT_K );
1027 + }
1165 1028
1166 - if ( ! is_array( $group_ids ) ) {
1167 - $group_ids = array();
1168 - }
1029 + public function getNotEmptyGroups( $userid = null, $enableOfflineSites = true ) {
1030 + if ( ( $userid == null ) && MainWP_System::Instance()->isMultiUser() ) {
1031 + global $current_user;
1032 + $userid = $current_user->ID;
1033 + }
1169 1034
1170 - // valid group ids.
1171 - $group_ids = array_filter(
1172 - $group_ids,
1173 - function ( $e ) {
1174 - if ( 'nogroups' === $e ) {
1175 - return true;
1176 - }
1177 - return ( is_numeric( $e ) && 0 < $e ) ? true : false;
1178 - }
1179 - );
1035 + $where = ' WHERE 1 ';
1036 + $where .= $this->getWhereAllowGroups( 'g' );
1180 1037
1181 - if ( ! is_array( $client_ids ) ) {
1182 - $client_ids = array();
1183 - }
1038 + if ( $userid != null ) {
1039 + $where .= ' AND g.userid = ' . $userid;
1040 + }
1041 + if ( !$enableOfflineSites ) {
1042 + $where .= ' AND wp_sync.sync_errors = ""';
1043 + }
1184 1044
1185 - // valid group ids.
1186 - $client_ids = array_filter(
1187 - $client_ids,
1188 - function ( $e ) {
1189 - if ( 'noclients' === $e ) {
1190 - return true;
1191 - }
1192 - return is_numeric( $e ) && ! empty( $e ) ? true : false; // to valid client ids.
1193 - }
1194 - );
1045 + return $this->wpdb->get_results( 'SELECT DISTINCT(g.id), g.name, count(wp.wpid)
1046 + FROM ' . $this->tableName( 'group' ) . ' g
1047 + JOIN ' . $this->tableName( 'wp_group' ) . ' wp ON g.id = wp.groupid
1048 + JOIN ' . $this->tableName( 'wp' ) . ' wpsite ON wp.wpid = wpsite.id
1049 + JOIN ' . $this->tableName( 'wp_sync' ) . ' wp_sync ON wp.wpid = wp_sync.wpid
1050 + ' . $where . '
1051 + GROUP BY g.id
1052 + HAVING count(wp.wpid) > 0
1053 + ORDER BY g.name', OBJECT_K );
1054 + }
1195 1055
1196 - if ( $selectgroups ) {
1197 - $staging_group = get_option( 'mainwp_stagingsites_group_id' );
1198 - if ( $staging_group && in_array( $staging_group, $group_ids ) ) {
1199 - if ( empty( $group_ids ) ) {
1200 - $is_staging = 'yes';
1201 - } else {
1202 - $is_staging = 'nocheckstaging';
1203 - }
1204 - }
1205 - }
1056 + public function getWebsitesByUrl( $url ) {
1057 + if ( substr( $url, - 1 ) != '/' ) {
1058 + $url .= '/';
1059 + }
1060 + $where = '';
1061 + $results = $this->wpdb->get_results( 'SELECT * FROM ' . $this->tableName( 'wp' ) . ' WHERE url = "' . $this->escape( $url ) . '"' . $where, OBJECT );
1062 + if ( $results ) {
1063 + return $results;
1064 + }
1206 1065
1207 - if ( ! is_array( $selected_sites ) ) {
1208 - $selected_sites = array();
1209 - }
1210 - $selected_sites = MainWP_Utility::array_numeric_filter( $selected_sites );
1066 + if ( stristr( $url, '/www.' ) ) {
1067 + //remove www if it's there!
1068 + $url = str_replace( '/www.', '/', $url );
1069 + } else {
1070 + //add www if it's not there!
1071 + $url = str_replace( 'https://', 'https://www.', $url );
1072 + $url = str_replace( 'http://', 'http://www.', $url );
1073 + }
1211 1074
1212 - $where = '';
1213 - if ( MainWP_System::instance()->is_multi_user() ) {
1075 + return $this->wpdb->get_results( 'SELECT * FROM ' . $this->tableName( 'wp' ) . ' WHERE url = "' . $this->escape( $url ) . '"' . $where, OBJECT );
1076 + }
1214 1077
1215 - /**
1216 - * Current user global.
1217 - *
1218 - * @global string
1219 - */
1220 - global $current_user;
1078 + public function getWebsiteBackupSettings( $websiteid ) {
1079 + if ( !MainWP_Utility::ctype_digit( $websiteid ) ) {
1080 + return null;
1081 + }
1221 1082
1222 - $where .= ' AND wp.userid = ' . $current_user->ID . ' ';
1223 - }
1083 + return $this->getRowResult( 'SELECT * FROM ' . $this->tableName( 'wp_settings_backup' ) . ' WHERE wpid = ' . $websiteid );
1084 + }
1224 1085
1225 - if ( ! empty( $selected_sites ) ) {
1226 - $where .= ' AND wp.id IN (' . implode( ',', $selected_sites ) . ') ';
1227 - }
1086 + public function getWebsiteById( $id, $selectGroups = false ) {
1087 + return $this->getRowResult( $this->getSQLWebsiteById( $id, $selectGroups ) );
1088 + }
1228 1089
1229 - // for searching.
1230 - if ( null !== $search_site && '' !== $search_site ) {
1231 - $where .= ' AND (wp.name LIKE "%' . $search_site . '%" OR wp.url LIKE "%' . $search_site . '%") ';
1232 - }
1090 + public function getSQLWebsiteById( $id, $selectGroups = false, $extra_view = array( 'favi_icon' ) ) {
1091 + if ( MainWP_Utility::ctype_digit( $id ) ) {
1092 + $where = $this->getWhereAllowAccessSites( 'wp', 'nocheckstaging' ); // no check staging
1093 + if ( $selectGroups ) {
1094 + return 'SELECT wp.*,wp_sync.*,wp_optionview.*, GROUP_CONCAT(gr.name ORDER BY gr.name SEPARATOR ", ") as wpgroups
1095 + FROM ' . $this->tableName( 'wp' ) . ' wp
1096 + LEFT JOIN ' . $this->tableName( 'wp_group' ) . ' wpgr ON wp.id = wpgr.wpid
1097 + LEFT JOIN ' . $this->tableName( 'group' ) . ' gr ON wpgr.groupid = gr.id
1098 + JOIN ' . $this->tableName( 'wp_sync' ) . ' wp_sync ON wp.id = wp_sync.wpid
1099 + JOIN ' . $this->getOptionView( $extra_view ) . ' wp_optionview ON wp.id = wp_optionview.wpid
1100 + WHERE wp.id = ' . $id . $where . '
1101 + GROUP BY wp.id';
1102 + }
1233 1103
1234 - if ( null !== $extraWhere ) {
1235 - $where .= ' AND ' . $extraWhere;
1236 - }
1104 + return 'SELECT wp.*,wp_sync.*,wp_optionview.*
1105 + FROM ' . $this->tableName( 'wp' ) . ' wp
1106 + JOIN ' . $this->tableName( 'wp_sync' ) . ' wp_sync ON wp.id = wp_sync.wpid
1107 + JOIN ' . $this->getOptionView( $extra_view ) . ' wp_optionview ON wp.id = wp_optionview.wpid
1108 + WHERE id = ' . $id . $where;
1109 + }
1237 1110
1238 - if ( ! $for_manager ) {
1239 - $where .= $this->get_sql_where_allow_access_sites( 'wp', $is_staging );
1240 - }
1111 + return null;
1112 + }
1241 1113
1242 - if ( $is_count ) {
1243 - $orderBy = '';
1244 - } elseif ( 'wp.url' === $orderBy ) {
1245 - $orderBy = "replace(replace(replace(replace(replace(wp.url, 'https://www.',''), 'http://www.',''), 'https://', ''), 'http://', ''), 'www.', '')";
1246 - }
1114 + public function getWebsitesByIds( $ids, $userId = null ) {
1115 + if ( ( $userId == null ) && MainWP_System::Instance()->isMultiUser() ) {
1116 + global $current_user;
1117 + $userId = $current_user->ID;
1118 + }
1119 + $where = $this->getWhereAllowAccessSites();
1247 1120
1248 - if ( ! empty( $orderBy ) ) {
1249 - $orderBy = ' ORDER BY ' . $orderBy;
1250 - }
1121 + return $this->wpdb->get_results( 'SELECT * FROM ' . $this->tableName( 'wp' ) . ' WHERE id IN (' . implode( ',', $ids ) . ')' . ( $userId != null ? ' AND userid = ' . $userId : '' ) . $where, OBJECT );
1122 + }
1251 1123
1252 - $join_group = '';
1253 - $where_group = '';
1124 + public function getWebsitesByGroupIds( $ids, $userId = null ) {
1125 + if ( empty( $ids ) ) {
1126 + return array();
1127 + }
1128 + if ( ( $userId == null ) && MainWP_System::Instance()->isMultiUser() ) {
1129 + global $current_user;
1130 + $userId = $current_user->ID;
1131 + }
1254 1132
1255 - if ( in_array( 'nogroups', $group_ids ) ) {
1256 - $join_group = ' LEFT JOIN ' . $this->table_name( 'wp_group' ) . ' wpgroup ON wp.id = wpgroup.wpid ';
1257 - $group_ids = array_filter(
1258 - $group_ids,
1259 - function ( $e ) {
1260 - return 'nogroups' !== $e;
1261 - }
1262 - );
1263 - if ( ! empty( $group_ids ) ) {
1264 - $groups = implode( ',', $group_ids );
1265 - if ( $is_not ) {
1266 - $where_group = ' AND wpgroup.groupid IS NOT NULL AND wpgroup.groupid NOT IN (' . $groups . ') ';
1267 - // to fix.
1268 - $sub_select_is_not = ' SELECT wp.id FROM ' . $this->table_name( 'wp' ) . ' wp JOIN ' . $this->table_name( 'wp_group' ) . ' wpgroup ON wp.id = wpgroup.wpid WHERE wpgroup.groupid IN (' . $groups . ') ';
1269 - $where_group .= ' AND wp.id NOT IN ( ' . $sub_select_is_not . ' ) ';
1270 - } else {
1271 - $where_group = ' AND ( wpgroup.groupid IS NULL OR wpgroup.groupid IN (' . $groups . ') ) ';
1272 - }
1273 - } elseif ( $is_not ) {
1274 - $where_group = ' AND wpgroup.groupid IS NOT NULL ';
1275 - } else {
1276 - $where_group = ' AND wpgroup.groupid IS NULL ';
1277 - }
1278 - } elseif ( $group_ids ) {
1279 - $groups = implode( ',', $group_ids );
1280 - if ( $is_not ) {
1281 - $join_group = ' LEFT JOIN ' . $this->table_name( 'wp_group' ) . ' wpgroup ON wp.id = wpgroup.wpid ';
1282 - $where_group = ' AND ( wpgroup.groupid NOT IN (' . $groups . ') OR wpgroup.groupid IS NULL ) ';
1283 - // to fix.
1284 - $sub_select_is_not = ' SELECT wp.id FROM ' . $this->table_name( 'wp' ) . ' wp JOIN ' . $this->table_name( 'wp_group' ) . ' wpgroup ON wp.id = wpgroup.wpid WHERE wpgroup.groupid IN (' . $groups . ') ';
1285 - $where_group .= ' AND wp.id NOT IN ( ' . $sub_select_is_not . ' ) ';
1286 - } else {
1287 - $join_group = ' JOIN ' . $this->table_name( 'wp_group' ) . ' wpgroup ON wp.id = wpgroup.wpid ';
1288 - $where_group = ' AND wpgroup.groupid IN (' . $groups . ') ';
1289 - }
1290 - }
1133 + return $this->wpdb->get_results( 'SELECT * FROM ' . $this->tableName( 'wp' ) . ' wp JOIN ' . $this->tableName( 'wp_group' ) . ' wpgroup ON wp.id = wpgroup.wpid WHERE wpgroup.groupid IN (' . implode( ',', $ids ) . ') ' . ( $userId != null ? ' AND wp.userid = ' . $userId : '' ), OBJECT );
1134 + }
1291 1135
1292 - $select_groups_belong = '';
1136 + public function getWebsitesByGroupId( $id ) {
1137 + return $this->getResultsResult( $this->getSQLWebsitesByGroupId( $id ) );
1138 + }
1293 1139
1294 - if ( ! $is_count && $group_ids ) {
1295 - $select_groups_belong = $this->get_select_groups_belong();
1296 - }
1140 + public function getSQLWebsitesByGroupId( $id, $selectgroups = false, $orderBy = 'wp.url', $offset = false,
1141 + $rowcount = false, $where = null, $search_site = null) {
1297 1142
1298 - $join_client = '';
1299 - $where_client = '';
1143 + $is_staging = 'no';
1144 + if ( $selectgroups ) {
1145 + if ( $staging_group = get_option( 'mainwp_stagingsites_group_id' ) ) {
1146 + if ( $id == $staging_group ) {
1147 + $is_staging = 'yes'; // will list staging sites
1148 + }
1149 + }
1150 + }
1300 1151
1301 - if ( in_array( 'noclients', $client_ids ) ) {
1302 - $join_client = ' LEFT JOIN ' . $this->table_name( 'wp_clients' ) . ' wpclient ON wp.client_id = wpclient.client_id ';
1303 - $client_ids = array_filter(
1304 - $client_ids,
1305 - function ( $e ) {
1306 - return 'noclients' !== $e;
1307 - }
1308 - );
1309 - if ( ! empty( $client_ids ) ) {
1310 - $clients = implode( ',', $client_ids );
1311 - if ( $is_not ) {
1312 - $where_client = ' AND wpclient.client_id IS NOT NULL AND wp.client_id NOT IN (' . $clients . ') ';
1313 - } else {
1314 - $where_client = ' AND wpclient.client_id IN (' . $clients . ') ';
1315 - }
1316 - } elseif ( $is_not ) {
1317 - $where_client = ' AND wpclient.client_id IS NOT NULL ';
1318 - } else {
1319 - $where_client = ' AND wpclient.client_id IS NULL ';
1320 - }
1321 - } elseif ( $client_ids && ! empty( $client_ids ) ) {
1322 - $clients = implode( ',', $client_ids );
1323 - if ( $is_not ) {
1324 - $join_client = ' LEFT JOIN ' . $this->table_name( 'wp_clients' ) . ' wpclient ON wp.client_id = wpclient.client_id ';
1325 - $where_client = ' AND ( wpclient.client_id NOT IN (' . $clients . ') OR wpclient.client_id IS NULL ) ';
1326 - } else {
1327 - $join_client = ' JOIN ' . $this->table_name( 'wp_clients' ) . ' wpclient ON wp.client_id = wpclient.client_id ';
1328 - $where_client = ' AND wpclient.client_id IN (' . $clients . ') ';
1329 - }
1330 - }
1152 + $where_search = '';
1153 + if ( !empty( $search_site ) ) {
1154 + $search_site = trim( $search_site );
1155 + $where_search .= ' AND (wp.name LIKE "%' . $this->escape( $search_site ) . '%" OR wp.url LIKE "%' . $this->escape( $search_site ) . '%") ';
1156 + }
1331 1157
1332 - if ( '' === $join_client ) {
1333 - $join_client = ' LEFT JOIN ' . $this->table_name( 'wp_clients' ) . ' wpclient ON wp.client_id = wpclient.client_id ';
1334 - }
1335 - // wpgroups to fix issue for mysql 8.0, as groups will generate error syntax.
1336 - if ( $selectgroups ) {
1158 + if ( MainWP_Utility::ctype_digit( $id ) ) {
1159 + $where_allowed = $this->getWhereAllowAccessSites( 'wp', $is_staging );
1160 + if ( $selectgroups ) {
1161 + $qry = 'SELECT wp.*,wp_sync.*,wp_optionview.*, GROUP_CONCAT(gr.name ORDER BY gr.name SEPARATOR ", ") as wpgroups
1162 + FROM ' . $this->tableName( 'wp' ) . ' wp
1163 + JOIN ' . $this->tableName( 'wp_group' ) . ' wpgroup ON wp.id = wpgroup.wpid
1164 + LEFT JOIN ' . $this->tableName( 'wp_group' ) . ' wpgr ON wp.id = wpgr.wpid
1165 + LEFT JOIN ' . $this->tableName( 'group' ) . ' gr ON wpgr.groupid = gr.id
1166 + JOIN ' . $this->tableName( 'wp_sync' ) . ' wp_sync ON wp.id = wp_sync.wpid
1167 + JOIN ' . $this->getOptionView() . ' wp_optionview ON wp.id = wp_optionview.wpid
1168 + WHERE wpgroup.groupid = ' . $id . ' ' .
1169 + ( $where == null ? '' : ' AND ' . $where ) . $where_allowed . $where_search . '
1170 + GROUP BY wp.id
1171 + ORDER BY ' . $orderBy;
1172 + } else {
1173 + $qry = 'SELECT wp.*,wp_sync.* FROM ' . $this->tableName( 'wp' ) . ' wp
1174 + JOIN ' . $this->tableName( 'wp_group' ) . ' wpgroup ON wp.id = wpgroup.wpid
1175 + JOIN ' . $this->tableName( 'wp_sync' ) . ' wp_sync ON wp.id = wp_sync.wpid
1176 + WHERE wpgroup.groupid = ' . $id . ' ' . $where_allowed . $where_search .
1177 + ( $where == null ? '' : ' AND ' . $where ) . ' ORDER BY ' . $orderBy;
1178 + }
1179 + if ( ( $offset !== false ) && ( $rowcount !== false ) ) {
1180 + $qry .= ' LIMIT ' . $offset . ', ' . $rowcount;
1181 + }
1337 1182
1338 - if ( empty( $join_group ) ) {
1339 - $join_group = ' LEFT JOIN ' . $this->table_name( 'wp_group' ) . ' wpgroup ON wp.id = wpgroup.wpid ';
1340 - }
1183 + return $qry;
1184 + }
1341 1185
1342 - $qry = 'SELECT wp.*,wp_sync.*,wp_optionview.*, GROUP_CONCAT(gr.name ORDER BY gr.name SEPARATOR ",") as wpgroups, GROUP_CONCAT(gr.id ORDER BY gr.name SEPARATOR ",") as wpgroupids, GROUP_CONCAT(gr.color ORDER BY gr.name SEPARATOR ",") as wpgroups_colors, wpclient.name as client_name ' .
1343 - $select_groups_belong . ' FROM ' . $this->table_name( 'wp' ) . ' wp ' .
1344 - $join_client . ' ' .
1345 - $join_group . '
1346 - LEFT JOIN ' . $this->table_name( 'group' ) . ' gr ON wpgroup.groupid = gr.id
1186 + return null;
1187 + }
1347 1188
1348 - JOIN ' . $this->table_name( 'wp_sync' ) . ' wp_sync ON wp.id = wp_sync.wpid
1349 - JOIN ' . $this->get_option_view( $extra_view ) . ' wp_optionview ON wp.id = wp_optionview.wpid
1350 - WHERE 1 ' . $where . $where_group . $where_client . '
1351 - GROUP BY wp.id, wp_sync.sync_id ' .
1352 - $orderBy;
1353 - } else {
1354 - $qry = 'SELECT wp.*,wp_sync.*,wp_optionview.*, wpclient.name as client_name ' .
1355 - $select_groups_belong . ' FROM ' . $this->table_name( 'wp' ) . ' wp ' .
1356 - $join_group . ' ' .
1357 - $join_client . '
1358 - JOIN ' . $this->table_name( 'wp_sync' ) . ' wp_sync ON wp.id = wp_sync.wpid
1359 - JOIN ' . $this->get_option_view( $extra_view ) . ' wp_optionview ON wp.id = wp_optionview.wpid
1360 - WHERE 1 ' . $where . $where_group . $where_client . '
1361 - GROUP BY wp.id, wp_sync.sync_id ' .
1362 - $orderBy;
1363 - }
1189 + public function getWebsitesByGroupName( $userid, $groupname ) {
1190 + return $this->getResultsResult( $this->getSQLWebsitesByGroupName( $groupname, $userid ) );
1191 + }
1364 1192
1365 - if ( ( false !== $offset ) && ( false !== $rowcount ) ) {
1366 - $qry .= ' LIMIT ' . $offset . ', ' . $rowcount;
1367 - } elseif ( false !== $rowcount ) {
1368 - $qry .= ' LIMIT ' . $rowcount;
1369 - }
1370 - //phpcs:ignore
1371 - // error_log( $qry ); // NOSONAR - for dev.
1372 - return $qry;
1373 - }
1193 + public function getSQLWebsitesByGroupName( $groupname, $userid = null ) {
1194 + if ( ( $userid == null ) && MainWP_System::Instance()->isMultiUser() ) {
1195 + global $current_user;
1196 + $userid = $current_user->ID;
1197 + }
1374 1198
1375 - /**
1376 - * Get child sites where allowed access via SQL.
1377 - *
1378 - * @param string $site_table_alias Child site table alias.
1379 - * @param string $is_staging yes|no Is child site a staging site.
1380 - *
1381 - * @return boolean|null $_where Database query results or null on failure.
1382 - */
1383 - public function get_sql_where_allow_access_sites( $site_table_alias = '', $is_staging = 'no' ) { // phpcs:ignore -- NOSONAR - complex.
1199 + $sql = 'SELECT wp.*,wp_sync.*,wp_optionview.* FROM ' . $this->tableName( 'wp' ) . ' wp
1200 + INNER JOIN ' . $this->tableName( 'wp_group' ) . ' wpgroup ON wp.id = wpgroup.wpid
1201 + JOIN ' . $this->tableName( 'group' ) . ' g ON wpgroup.groupid = g.id
1202 + JOIN ' . $this->tableName( 'wp_sync' ) . ' wp_sync ON wp.id = wp_sync.wpid
1203 + JOIN ' . $this->getOptionView() . ' wp_optionview ON wp.id = wp_optionview.wpid
1204 + WHERE g.name="' . $this->escape( $groupname ) . '"';
1205 + if ( $userid != null ) {
1206 + $sql .= ' AND g.userid = "' . $userid . '"';
1207 + }
1384 1208
1385 - if ( empty( $site_table_alias ) ) {
1386 - $site_table_alias = $this->table_name( 'wp' );
1387 - }
1209 + return $sql;
1210 + }
1388 1211
1389 - // check to filter the staging sites.
1390 - $where_staging = ' AND ' . $site_table_alias . '.is_staging = 0 ';
1391 - if ( 'no' === $is_staging ) {
1392 - $where_staging = ' AND ' . $site_table_alias . '.is_staging = 0 ';
1393 - } elseif ( 'yes' === $is_staging ) {
1394 - $where_staging = ' AND ' . $site_table_alias . '.is_staging = 1 ';
1395 - } elseif ( 'nocheckstaging' === $is_staging ) {
1396 - $where_staging = '';
1397 - }
1398 - // end staging filter.
1212 + public function getWPIp( $wpid ) {
1213 + return $this->wpdb->get_var( 'SELECT ip FROM ' . $this->tableName( 'request_log' ) . ' WHERE wpid = "' . $wpid . '"' );
1214 + }
1399 1215
1400 - $_where = $where_staging;
1401 - // To fix bug run from cron job.
1402 - if ( defined( 'DOING_CRON' ) && DOING_CRON ) {
1403 - return $_where;
1404 - }
1216 + public function insertOrUpdateRequestLog( $wpid, $ip, $start, $stop ) {
1217 + $updateValues = array();
1218 + if ( $ip != null ) {
1219 + $updateValues[ 'ip' ] = $ip;
1220 + }
1221 + if ( $start != null ) {
1222 + $updateValues[ 'micro_timestamp_start' ] = $start;
1223 + }
1224 + if ( $stop != null ) {
1225 + $updateValues[ 'micro_timestamp_stop' ] = $stop;
1226 + }
1405 1227
1406 - // To fix bug run from wp cli.
1407 - if ( defined( 'WP_CLI' ) && WP_CLI ) {
1408 - return $_where;
1409 - }
1228 + $var = $this->wpdb->get_var( 'SELECT id FROM ' . $this->tableName( 'request_log' ) . ' WHERE wpid = "' . $wpid . '"' );
1229 + if ( $var !== null ) {
1230 + $this->wpdb->update( $this->tableName( 'request_log' ), $updateValues, array( 'wpid' => $wpid ) );
1231 + } else {
1232 + $updateValues[ 'wpid' ] = $wpid;
1233 + $this->wpdb->insert( $this->tableName( 'request_log' ), $updateValues );
1234 + }
1235 + }
1410 1236
1411 - // Run from Rest Api.
1412 - if ( defined( 'MAINWP_REST_API_DOING' ) && MAINWP_REST_API_DOING ) {
1413 - return $_where;
1414 - }
1237 + public function closeOpenRequests() {
1238 + //Close requests open longer then 7 seconds.. something is wrong here..
1239 + $this->wpdb->query( 'UPDATE ' . $this->tableName( 'request_log' ) . ' SET micro_timestamp_stop = micro_timestamp_start WHERE micro_timestamp_stop < micro_timestamp_start and ' . microtime( true ) . ' - micro_timestamp_start > 7' );
1240 + }
1415 1241
1416 - /**
1417 - * Filter: mainwp_currentuserallowedaccesssites
1418 - *
1419 - * Filters allowed sites for the current user.
1420 - *
1421 - * @since Unknown
1422 - */
1423 - $allowed_sites = apply_filters( 'mainwp_currentuserallowedaccesssites', 'all' );
1242 + public function getNrOfOpenRequests( $ip = null ) {
1243 + if ( $ip == null ) {
1244 + return $this->wpdb->get_var( 'select count(id) from ' . $this->tableName( 'request_log' ) . ' where micro_timestamp_stop < micro_timestamp_start' );
1245 + }
1424 1246
1425 - if ( 'all' === $allowed_sites ) {
1426 - return $_where;
1427 - }
1247 + return $this->wpdb->get_var( 'select count(id) from ' . $this->tableName( 'request_log' ) . ' where micro_timestamp_stop < micro_timestamp_start and ip = "' . esc_sql( $ip ) . '"' );
1248 + }
1428 1249
1429 - if ( is_array( $allowed_sites ) && ! empty( $allowed_sites ) ) {
1430 - // valid group ids.
1431 - $allowed_sites = array_filter(
1432 - $allowed_sites,
1433 - function ( $e ) {
1434 - return is_numeric( $e ) ? true : false;
1435 - }
1436 - );
1437 - $_where .= ' AND ' . $site_table_alias . '.id IN (' . implode( ',', $allowed_sites ) . ') ';
1438 - } else {
1439 - $_where .= ' AND 0 ';
1440 - }
1250 + public function getLastRequestTimestamp( $ip = null ) {
1251 + if ( $ip == null ) {
1252 + return $this->wpdb->get_var( 'select micro_timestamp_start from ' . $this->tableName( 'request_log' ) . ' order by micro_timestamp_start desc limit 1' );
1253 + }
1441 1254
1442 - return $_where;
1443 - }
1255 + return $this->wpdb->get_var( 'SELECT micro_timestamp_start FROM ' . $this->tableName( 'request_log' ) . ' WHERE ip = "' . esc_sql( $ip ) . '" order by micro_timestamp_start desc limit 1' );
1256 + }
1444 1257
1445 - /**
1446 - * Get groupd where allowed access via SQL.
1447 - *
1448 - * @param string $group_table_alias Child site table alias.
1449 - * @param string $with_staging yes|no Is child site a staging site.
1450 - *
1451 - * @return boolean|null $_where Database query results or null on failer.
1452 - */
1453 - public function get_sql_where_allow_groups( $group_table_alias = '', $with_staging = 'no' ) { // phpcs:ignore -- NOSONAR - complex.
1258 + public function addWebsite( $userid, $name, $url, $admin, $pubkey, $privkey, $nossl, $nosslkey, $groupids, $groupnames,
1259 + $verifyCertificate = 1, $uniqueId = '', $http_user, $http_pass, $sslVersion = 0, $wpe = 0, $isStaging = 0 ) {
1260 + if ( MainWP_Utility::ctype_digit( $userid ) && ( $nossl == 0 || $nossl == 1 ) ) {
1261 + $values = array(
1262 + 'userid' => $userid,
1263 + 'adminname' => $this->escape( $admin ),
1264 + 'name' => $this->escape( strip_tags( $name ) ), // escape by insert
1265 + 'url' => $this->escape( $url ),
1266 + 'pubkey' => $this->escape( $pubkey ),
1267 + 'privkey' => $this->escape( $privkey ),
1268 + 'nossl' => $nossl,
1269 + 'nosslkey' => ( $nosslkey == null ? '' : $this->escape( $nosslkey ) ),
1270 + 'siteurl' => '',
1271 + 'ga_id' => '',
1272 + 'gas_id' => 0,
1273 + 'offline_checks' => '',
1274 + 'offline_checks_last' => 0,
1275 + 'offline_check_result' => 0,
1276 + 'note' => '',
1277 + 'statsUpdate' => 0,
1278 + 'pagerank' => 0,
1279 + 'indexed' => 0,
1280 + 'alexia' => 0,
1281 + 'pagerank_old' => 0,
1282 + 'indexed_old' => 0,
1283 + 'alexia_old' => 0,
1284 + 'directories' => '',
1285 + 'plugin_upgrades' => '',
1286 + 'theme_upgrades' => '',
1287 + 'translation_upgrades' => '',
1288 + 'securityIssues' => '',
1289 + 'themes' => '',
1290 + 'ignored_themes' => '',
1291 + 'plugins' => '',
1292 + 'ignored_plugins' => '',
1293 + 'pages' => '',
1294 + 'users' => '',
1295 + 'categories' => '',
1296 + 'pluginDir' => '',
1297 + 'automatic_update' => 0,
1298 + 'backup_before_upgrade' => 2,
1299 + 'verify_certificate' => intval( $verifyCertificate ),
1300 + 'ssl_version' => $sslVersion,
1301 + 'uniqueId' => $uniqueId,
1302 + 'mainwpdir' => 0,
1303 + 'http_user' => $http_user,
1304 + 'http_pass' => $http_pass,
1305 + 'wpe' => $wpe,
1306 + 'is_staging' => $isStaging
1307 + );
1454 1308
1455 - if ( empty( $group_table_alias ) ) {
1456 - $group_table_alias = $this->table_name( 'group' );
1457 - }
1309 + $syncValues = array(
1310 + 'dtsSync' => 0,
1311 + 'dtsSyncStart' => 0,
1312 + 'dtsAutomaticSync' => 0,
1313 + 'dtsAutomaticSyncStart' => 0,
1314 + 'totalsize' => 0,
1315 + 'extauth' => '',
1316 + 'sync_errors' => '',
1317 + );
1318 + if ( $this->wpdb->insert( $this->tableName( 'wp' ), $values ) ) {
1319 + $websiteid = $this->wpdb->insert_id;
1320 + $syncValues[ 'wpid' ] = $websiteid;
1321 + $this->wpdb->insert( $this->tableName( 'wp_sync' ), $syncValues );
1322 + $this->wpdb->insert( $this->tableName( 'wp_settings_backup' ), array(
1323 + 'wpid' => $websiteid,
1324 + 'archiveFormat' => 'global',
1325 + ) );
1458 1326
1459 - // check to filter the staging group.
1460 - $where_staging_group = '';
1461 - $staging_group = get_option( 'mainwp_stagingsites_group_id' );
1462 - if ( $staging_group ) {
1463 - $where_staging_group = ' AND ' . $group_table_alias . '.id <> ' . $staging_group . ' ';
1464 - if ( 'yes' === $with_staging ) {
1465 - $where_staging_group = '';
1466 - }
1467 - }
1327 + foreach ( $groupnames as $groupname ) {
1328 + if ( $this->wpdb->insert( $this->tableName( 'group' ), array(
1329 + 'userid' => $userid,
1330 + 'name' => $this->escape( htmlspecialchars( $groupname ) ),
1331 + ) )
1332 + ) {
1333 + $groupids[] = $this->wpdb->insert_id;
1334 + }
1335 + }
1336 + //add groupids
1337 + foreach ( $groupids as $groupid ) {
1338 + $this->wpdb->insert( $this->tableName( 'wp_group' ), array(
1339 + 'wpid' => $websiteid,
1340 + 'groupid' => $groupid,
1341 + ) );
1342 + }
1468 1343
1469 - // end staging filter.
1470 - $_where = $where_staging_group;
1344 + return $websiteid;
1345 + }
1346 + }
1471 1347
1472 - // To fix bug run from cron job.
1473 - if ( defined( 'DOING_CRON' ) && DOING_CRON ) {
1474 - return $_where;
1475 - }
1348 + return false;
1349 + }
1476 1350
1477 - // Run from wp cli.
1478 - if ( defined( 'WP_CLI' ) && WP_CLI ) {
1479 - return $_where;
1480 - }
1351 + public function updateGroupSite( $groupId, $websiteId ) {
1352 + $this->wpdb->insert( $this->tableName( 'wp_group' ), array( 'wpid' => $websiteId, 'groupid' => $groupId ) );
1353 + }
1481 1354
1482 - // Run from Rest Api.
1483 - if ( defined( 'MAINWP_REST_API_DOING' ) && MAINWP_REST_API_DOING ) {
1484 - return $_where;
1485 - }
1355 + public function clearGroup( $groupId ) {
1356 + $this->wpdb->query( 'DELETE FROM ' . $this->tableName( 'wp_group' ) . ' WHERE groupid=' . $groupId );
1357 + }
1486 1358
1487 - /**
1488 - * Filter: mainwp_currentuserallowedaccessgroups
1489 - *
1490 - * Filters allowed groups for the current user.
1491 - *
1492 - * @since Unknown
1493 - */
1494 - $allowed_groups = apply_filters( 'mainwp_currentuserallowedaccessgroups', 'all' );
1359 + public function addGroup( $userid, $name ) {
1360 + if ( MainWP_Utility::ctype_digit( $userid ) ) {
1361 + if ( $this->wpdb->insert( $this->tableName( 'group' ), array(
1362 + 'userid' => $userid,
1363 + 'name' => $this->escape( $name ),
1364 + ) )
1365 + ) {
1366 + return $this->wpdb->insert_id;
1367 + }
1368 + }
1495 1369
1496 - if ( 'all' === $allowed_groups ) {
1497 - return $_where;
1498 - }
1370 + return false;
1371 + }
1499 1372
1500 - if ( is_array( $allowed_groups ) && ! empty( $allowed_groups ) ) {
1373 + public function removeWebsite( $websiteid ) {
1374 + if ( MainWP_Utility::ctype_digit( $websiteid ) ) {
1375 + $nr = $this->wpdb->query( 'DELETE FROM ' . $this->tableName( 'wp' ) . ' WHERE id=' . $websiteid );
1376 + $this->wpdb->query( 'DELETE FROM ' . $this->tableName( 'wp_group' ) . ' WHERE wpid=' . $websiteid );
1377 + $this->wpdb->query( 'DELETE FROM ' . $this->tableName( 'wp_sync' ) . ' WHERE wpid=' . $websiteid );
1378 + $this->wpdb->query( 'DELETE FROM ' . $this->tableName( 'wp_options' ) . ' WHERE wpid=' . $websiteid );
1501 1379
1502 - // valid group ids.
1503 - $allowed_groups = array_filter(
1504 - $allowed_groups,
1505 - function ( $e ) {
1506 - return is_numeric( $e ) ? true : false;
1507 - }
1508 - );
1380 + return $nr;
1381 + }
1509 1382
1510 - return ' AND ' . $group_table_alias . '.id IN (' . implode( ',', $allowed_groups ) . ') ' . $_where;
1511 - } else {
1512 - return ' AND 0 ';
1513 - }
1514 - }
1383 + return false;
1384 + }
1515 1385
1516 - /**
1517 - * Get child site by id.
1518 - *
1519 - * @param int $id Child site ID.
1520 - * @param array $selectGroups Select groups.
1521 - * @param array $extra_view Get extra option fields.
1522 - *
1523 - * @return object|null Database query results or null on failure.
1524 - */
1525 - public function get_website_by_id( $id, $selectGroups = false, $extra_view = array() ) {
1526 - return $this->get_row_result( $this->get_sql_website_by_id( $id, $selectGroups, $extra_view ) );
1527 - }
1386 + public function removeGroup( $groupid ) {
1387 + if ( MainWP_Utility::ctype_digit( $groupid ) ) {
1388 + $nr = $this->wpdb->query( 'DELETE FROM ' . $this->tableName( 'group' ) . ' WHERE id=' . $groupid );
1389 + $this->wpdb->query( 'DELETE FROM ' . $this->tableName( 'wp_group' ) . ' WHERE groupid=' . $groupid );
1528 1390
1529 - /**
1530 - * Get child site by id via SQL.
1531 - *
1532 - * @param int $id Child site ID.
1533 - * @param bool $selectGroups Selected groups.
1534 - * @param mixed $extra_view Extra view value.
1535 - *
1536 - * @return object|null Database query result or null on failure.
1537 - *
1538 - * @uses \MainWP\Dashboard\MainWP_Utility::ctype_digit()
1539 - */
1540 - public function get_sql_website_by_id( $id, $selectGroups = false, $extra_view = array() ) {
1391 + return $nr;
1392 + }
1541 1393
1542 - if ( ! is_array( $extra_view ) || empty( $extra_view ) ) {
1543 - $extra_view = array( 'favi_icon', 'site_info' );
1544 - }
1394 + return false;
1395 + }
1545 1396
1546 - if ( MainWP_Utility::ctype_digit( $id ) ) {
1547 - $where = $this->get_sql_where_allow_access_sites( 'wp', 'nocheckstaging' );
1548 - if ( $selectGroups ) {
1549 - return 'SELECT wp.*,wp_sync.*,wp_optionview.*, GROUP_CONCAT(gr.name ORDER BY gr.name SEPARATOR ",") as wpgroups, GROUP_CONCAT(gr.id ORDER BY gr.name SEPARATOR ",") as wpgroupids, GROUP_CONCAT(gr.color ORDER BY gr.name SEPARATOR ",") as wpgroups_colors
1550 - FROM ' . $this->table_name( 'wp' ) . ' wp
1551 - LEFT JOIN ' . $this->table_name( 'wp_group' ) . ' wpgr ON wp.id = wpgr.wpid
1552 - LEFT JOIN ' . $this->table_name( 'group' ) . ' gr ON wpgr.groupid = gr.id
1553 - JOIN ' . $this->table_name( 'wp_sync' ) . ' wp_sync ON wp.id = wp_sync.wpid
1554 - JOIN ' . $this->get_option_view( $extra_view ) . ' wp_optionview ON wp.id = wp_optionview.wpid
1555 - WHERE wp.id = ' . $id . $where . '
1556 - GROUP BY wp.id, wp_sync.sync_id';
1557 - }
1397 + public function updateNote( $websiteid, $note ) {
1398 + $this->wpdb->query( 'UPDATE ' . $this->tableName( 'wp' ) . ' SET note="' . $this->escape( $note ) . '", note_lastupdate = ' . time() . ' WHERE id=' . $websiteid );
1399 + }
1558 1400
1559 - return 'SELECT wp.*,wp_sync.*,wp_optionview.*
1560 - FROM ' . $this->table_name( 'wp' ) . ' wp
1561 - JOIN ' . $this->table_name( 'wp_sync' ) . ' wp_sync ON wp.id = wp_sync.wpid
1562 - JOIN ' . $this->get_option_view( $extra_view ) . ' wp_optionview ON wp.id = wp_optionview.wpid
1563 - WHERE id = ' . $id . $where;
1564 - }
1401 + public function updateWebsiteOfflineCheckSetting( $websiteid, $offlineChecks ) {
1402 + return $this->wpdb->query( 'UPDATE ' . $this->tableName( 'wp' ) . ' SET offline_checks="' . $this->escape( $offlineChecks ) . '" WHERE id=' . $websiteid, OBJECT );
1403 + }
1565 1404
1566 - return null;
1567 - }
1405 + public function updateWebsiteValues( $websiteid, $fields ) {
1406 + if ( count( $fields ) > 0 ) {
1407 + return $this->wpdb->update( $this->tableName( 'wp' ), $fields, array( 'id' => $websiteid ) );
1408 + }
1568 1409
1569 - /**
1570 - * Method get_websites_by_ids()
1571 - *
1572 - * Get child sites by child site IDs.
1573 - *
1574 - * @param array $ids Child site IDs.
1575 - * @param int $userId User ID.
1576 - *
1577 - * @return object|null Database query result or null on failure.
1578 - *
1579 - * @uses \MainWP\Dashboard\MainWP_System::is_multi_user()
1580 - */
1581 - public function get_websites_by_ids( $ids, $userId = null ) {
1582 - if ( ( null === $userId ) && MainWP_System::instance()->is_multi_user() ) {
1410 + return false;
1411 + }
1583 1412
1584 - /**
1585 - * Current user global.
1586 - *
1587 - * @global string
1588 - */
1589 - global $current_user;
1413 + public function updateWebsiteSyncValues( $websiteid, $fields ) {
1414 + if ( count( $fields ) > 0 ) {
1415 + return $this->wpdb->update( $this->tableName( 'wp_sync' ), $fields, array( 'wpid' => $websiteid ) );
1416 + }
1590 1417
1591 - $userId = $current_user->ID;
1592 - }
1418 + return false;
1419 + }
1593 1420
1594 - // valid group ids.
1595 - $ids = array_filter(
1596 - $ids,
1597 - function ( $e ) {
1598 - return ( is_numeric( $e ) && 0 < $e ) ? true : false;
1599 - }
1600 - );
1421 + public function updateWebsite( $websiteid, $url, $userid, $name, $siteadmin, $groupids, $groupnames, $offlineChecks,
1422 + $pluginDir, $maximumFileDescriptorsOverride, $maximumFileDescriptorsAuto, $maximumFileDescriptors,
1423 + $verifyCertificate = 1, $archiveFormat, $uniqueId = '', $http_user = null, $http_pass = null, $sslVersion = 0,
1424 + $wpe = 0 ) {
1425 + if ( MainWP_Utility::ctype_digit( $websiteid ) && MainWP_Utility::ctype_digit( $userid ) ) {
1426 + $website = MainWP_DB::Instance()->getWebsiteById( $websiteid );
1427 + if ( MainWP_Utility::can_edit_website( $website ) ) {
1428 + //update admin
1429 + $this->wpdb->query( 'UPDATE ' . $this->tableName( 'wp' ) . ' SET url="' . $this->escape( $url ) . '", name="' . $this->escape( strip_tags($name) ) . '", adminname="' . $this->escape( $siteadmin ) . '",offline_checks="' . $this->escape( $offlineChecks ) . '",pluginDir="' . $this->escape( $pluginDir ) . '",maximumFileDescriptorsOverride = ' . ( $maximumFileDescriptorsOverride ? 1 : 0 ) . ',maximumFileDescriptorsAuto= ' . ( $maximumFileDescriptorsAuto ? 1 : 0 ) . ',maximumFileDescriptors = ' . $maximumFileDescriptors . ', verify_certificate="' . intval( $verifyCertificate ) . '", ssl_version="' . intval( $sslVersion ) . '", wpe="' . intval( $wpe ) . '", uniqueId="' . $this->escape( $uniqueId ) . '", http_user="' . $this->escape( $http_user ) . '", http_pass="' . $this->escape( $http_pass ) . '" WHERE id=' . $websiteid );
1430 + $this->wpdb->query( 'UPDATE ' . $this->tableName( 'wp_settings_backup' ) . ' SET archiveFormat = "' . $this->escape( $archiveFormat ) . '" WHERE wpid=' . $websiteid );
1431 + //remove groups
1432 + $this->wpdb->query( 'DELETE FROM ' . $this->tableName( 'wp_group' ) . ' WHERE wpid=' . $websiteid );
1433 + //Remove GA stats
1434 + $showErrors = $this->wpdb->hide_errors();
1435 + do_action( 'mainwp_ga_delete_site', $websiteid );
1436 + if ( $showErrors ) {
1437 + $this->wpdb->show_errors();
1438 + }
1439 + //add groups with groupnames
1440 + foreach ( $groupnames as $groupname ) {
1441 + if ( $this->wpdb->insert( $this->tableName( 'group' ), array(
1442 + 'userid' => $userid,
1443 + 'name' => $this->escape( $groupname ),
1444 + ) )
1445 + ) {
1446 + $groupids[] = $this->wpdb->insert_id;
1447 + }
1448 + }
1449 + //add groupids
1450 + foreach ( $groupids as $groupid ) {
1451 + $this->wpdb->insert( $this->tableName( 'wp_group' ), array(
1452 + 'wpid' => $websiteid,
1453 + 'groupid' => $groupid,
1454 + ) );
1455 + }
1601 1456
1602 - $where = $this->get_sql_where_allow_access_sites();
1457 + return true;
1458 + }
1459 + }
1603 1460
1604 - return $this->wpdb->get_results( 'SELECT * FROM ' . $this->table_name( 'wp' ) . ' WHERE id IN (' . implode( ',', $ids ) . ')' . ( null !== $userId ? ' AND userid = ' . intval( $userId ) : '' ) . $where, OBJECT );
1605 - }
1461 + return false;
1462 + }
1606 1463
1607 - /**
1608 - * Get child sites by groups IDs.
1609 - *
1610 - * @param array $ids Groups IDs.
1611 - * @param int $userId User ID.
1612 - *
1613 - * @return object|null Database query result or null on failure.
1614 - *
1615 - * @uses \MainWP\Dashboard\MainWP_System::is_multi_user()
1616 - */
1617 - public function get_websites_by_group_ids( $ids, $userId = null ) {
1618 - if ( empty( $ids ) ) {
1619 - return array();
1620 - }
1621 - if ( ( null === $userId ) && MainWP_System::instance()->is_multi_user() ) {
1464 + public function updateGroup( $groupid, $groupname ) {
1465 + if ( MainWP_Utility::ctype_digit( $groupid ) ) {
1466 + //update groupname
1467 + $this->wpdb->query( 'UPDATE ' . $this->tableName( 'group' ) . ' SET name="' . $this->escape( $groupname ) . '" WHERE id=' . $groupid );
1622 1468
1623 - /**
1624 - * Current user global.
1625 - *
1626 - * @global string
1627 - */
1628 - global $current_user;
1469 + return true;
1470 + }
1629 1471
1630 - $userId = $current_user->ID;
1631 - }
1472 + return false;
1473 + }
1632 1474
1633 - // valid group ids.
1634 - $group_ids = array_filter(
1635 - $ids,
1636 - function ( $e ) {
1637 - return is_numeric( $e ) ? true : false;
1638 - }
1639 - );
1475 + public function updateBackupTaskProgress( $task_id, $wp_id, $values ) {
1476 + $this->wpdb->update( $this->tableName( 'wp_backup_progress' ), $values, array(
1477 + 'task_id' => $task_id,
1478 + 'wp_id' => $wp_id,
1479 + ) );
1640 1480
1641 - return $this->wpdb->get_results( 'SELECT * FROM ' . $this->table_name( 'wp' ) . ' wp JOIN ' . $this->table_name( 'wp_group' ) . ' wpgroup ON wp.id = wpgroup.wpid WHERE wpgroup.groupid IN (' . implode( ',', $group_ids ) . ') ' . ( null !== $userId ? ' AND wp.userid = ' . intval( $userId ) : '' ), OBJECT );
1642 - }
1481 + return $this->getBackupTaskProgress( $task_id, $wp_id );
1482 + }
1643 1483
1644 - /**
1645 - * Get child sites by group ID.
1646 - *
1647 - * @param int $id Group ID.
1648 - *
1649 - * @return object|null Database query result or null on failure.
1650 - */
1651 - public function get_websites_by_group_id( $id ) {
1652 - return $this->get_results_result( $this->get_sql_websites_by_group_id( $id ) );
1653 - }
1484 + public function addBackupTaskProgress( $task_id, $wp_id, $information ) {
1485 + $values = array(
1486 + 'task_id' => $task_id,
1487 + 'wp_id' => $wp_id,
1488 + 'dtsFetched' => time(),
1489 + 'fetchResult' => json_encode( $information ),
1490 + 'removedFiles' => 0,
1491 + 'downloadedDB' => '',
1492 + 'downloadedFULL' => '',
1493 + );
1654 1494
1655 - /**
1656 - * Get child sites by group id via SQL.
1657 - *
1658 - * @param int $id Group ID.
1659 - * @param bool $selectgroups Selected groups. Default: false.
1660 - * @param string $orderBy Order list by. Default: URL.
1661 - * @param bool $offset Query offset. Default: false.
1662 - * @param bool $rowcount Row count. Default: falese.
1663 - * @param null $where SQL WHERE value.
1664 - * @param null $search_site Site search field value. Default: null.
1665 - * @param array $others Others params.
1666 - *
1667 - * @return object|null Return database query or null on failure.
1668 - *
1669 - * @uses \MainWP\Dashboard\MainWP_Utility::ctype_digit()
1670 - */
1671 - public function get_sql_websites_by_group_id( // phpcs:ignore -- NOSONAR - complex.
1672 - $id,
1673 - $selectgroups = false,
1674 - $orderBy = 'wp.url',
1675 - $offset = false,
1676 - $rowcount = false,
1677 - $where = null,
1678 - $search_site = null,
1679 - $others = array()
1680 - ) {
1495 + if ( $this->wpdb->insert( $this->tableName( 'wp_backup_progress' ), $values ) ) {
1496 + return $this->getBackupTaskProgress( $task_id, $wp_id );
1497 + }
1681 1498
1682 - $is_staging = 'no';
1683 - if ( $selectgroups ) {
1684 - $staging_group = get_option( 'mainwp_stagingsites_group_id' );
1685 - if ( $staging_group && $id === $staging_group ) {
1686 - $is_staging = 'yes';
1687 - }
1688 - }
1499 + return null;
1500 + }
1689 1501
1690 - $where_search = '';
1691 - if ( ! empty( $search_site ) ) {
1692 - $search_site = trim( $search_site );
1693 - $where_search .= ' AND (wp.name LIKE "%' . $this->escape( $search_site ) . '%" OR wp.url LIKE "%' . $this->escape( $search_site ) . '%") ';
1694 - }
1502 + public function getBackupTaskProgress( $task_id, $wp_id ) {
1503 + $progress = $this->wpdb->get_row( 'SELECT * FROM ' . $this->tableName( 'wp_backup_progress' ) . ' WHERE task_id= ' . $task_id . ' AND wp_id = ' . $wp_id );
1695 1504
1696 - $extra_view = is_array( $others ) && isset( $others['extra_view'] ) && is_array( $others['extra_view'] ) && ! empty( $others['extra_view'] ) ? $others['extra_view'] : array( 'site_info' );
1505 + if ( $progress->fetchResult != '' ) {
1506 + $progress->fetchResult = json_decode( $progress->fetchResult, true );
1507 + }
1697 1508
1698 - if ( MainWP_Utility::ctype_digit( $id ) ) {
1699 - $where_allowed = $this->get_sql_where_allow_access_sites( 'wp', $is_staging );
1700 - if ( $selectgroups ) {
1701 - $qry = 'SELECT wp.*,wp_sync.*,wp_optionview.*, GROUP_CONCAT(gr.name ORDER BY gr.name SEPARATOR ",") as wpgroups, GROUP_CONCAT(gr.id ORDER BY gr.name SEPARATOR ",") as wpgroupids, GROUP_CONCAT(gr.color ORDER BY gr.name SEPARATOR ",") as wpgroups_colors
1702 - FROM ' . $this->table_name( 'wp' ) . ' wp
1703 - JOIN ' . $this->table_name( 'wp_group' ) . ' wpgroup ON wp.id = wpgroup.wpid
1704 - LEFT JOIN ' . $this->table_name( 'wp_group' ) . ' wpgr ON wp.id = wpgr.wpid
1705 - LEFT JOIN ' . $this->table_name( 'group' ) . ' gr ON wpgr.groupid = gr.id
1706 - JOIN ' . $this->table_name( 'wp_sync' ) . ' wp_sync ON wp.id = wp_sync.wpid
1707 - JOIN ' . $this->get_option_view( $extra_view, true ) . ' wp_optionview ON wp.id = wp_optionview.wpid
1708 - WHERE wpgroup.groupid = ' . $id . ' ' .
1709 - ( empty( $where ) ? '' : ' AND ' . $where ) . $where_allowed . $where_search . '
1710 - GROUP BY wp.id, wp_sync.sync_id
1711 - ORDER BY ' . $orderBy;
1712 - } else {
1713 - $qry = 'SELECT wp.*,wp_optionview.*, wp_sync.* FROM ' . $this->table_name( 'wp' ) . ' wp
1714 - JOIN ' . $this->table_name( 'wp_group' ) . ' wpgroup ON wp.id = wpgroup.wpid
1715 - JOIN ' . $this->table_name( 'wp_sync' ) . ' wp_sync ON wp.id = wp_sync.wpid
1716 - JOIN ' . $this->get_option_view( $extra_view, false ) . ' wp_optionview ON wp.id = wp_optionview.wpid
1717 - WHERE wpgroup.groupid = ' . $id . ' ' . $where_allowed . $where_search .
1718 - ( empty( $where ) ? '' : ' AND ' . $where ) . ' ORDER BY ' . $orderBy;
1719 - }
1720 - if ( ( false !== $offset ) && ( false !== $rowcount ) ) {
1721 - $qry .= ' LIMIT ' . $offset . ', ' . $rowcount;
1722 - } elseif ( false !== $rowcount ) {
1723 - $qry .= ' LIMIT ' . $rowcount;
1724 - }
1509 + return $progress;
1510 + }
1725 1511
1726 - return $qry;
1727 - }
1512 + public function backupFullTaskRunning( $wp_id ) {
1728 1513
1729 - return null;
1730 - }
1514 + if (!get_option('mainwp_enableLegacyBackupFeature')) {
1515 + return false;
1516 + }
1731 1517
1732 - /**
1733 - * Get child sites by group name.
1734 - *
1735 - * @param int $userid Current user ID.
1736 - * @param string $groupname Group name.
1737 - *
1738 - * @return object|null Database query result or null on failure.
1739 - */
1740 - public function get_websites_by_group_name( $userid, $groupname ) {
1741 - return $this->get_results_result( $this->get_sql_websites_by_group_name( $groupname, $userid ) );
1742 - }
1518 + $progresses = $this->wpdb->get_results( 'SELECT * FROM ' . $this->tableName( 'wp_backup_progress' ) . ' WHERE wp_id = ' . $wp_id . ' AND dtsFetched > ' . (time() - (30 * 60)) );
1519 + if ( is_array( $progresses ) ) {
1520 + foreach ( $progresses as $progress ) {
1521 + if ( ( $progress->downloadedDBComplete == 0 ) && ( $progress->downloadedFULLComplete == 0 ) ) {
1522 + if ( $task = $this->getBackupTaskById( $progress->task_id ) ) {
1523 + if ( ( 'full' == $task->type ) && !$task->paused ) {
1524 + return true;
1525 + }
1526 + }
1527 + }
1528 + }
1529 + }
1530 + return false;
1531 + }
1743 1532
1744 - /**
1745 - * Get child sites by group name.
1746 - *
1747 - * @param string $groupname Group name.
1748 - * @param int $userid Current user ID.
1749 - *
1750 - * @return object|null Database query result or null on failure.
1751 - *
1752 - * @uses \MainWP\Dashboard\MainWP_System::is_multi_user()
1753 - */
1754 - public function get_sql_websites_by_group_name( $groupname, $userid = null ) {
1755 - if ( ( null === $userid ) && MainWP_System::instance()->is_multi_user() ) {
1533 + public function removeBackupTask( $id ) {
1534 + $this->wpdb->query( 'DELETE FROM ' . $this->tableName( 'wp_backup' ) . ' WHERE id = ' . $id );
1535 + }
1756 1536
1757 - /**
1758 - * Current user global.
1759 - *
1760 - * @global string
1761 - */
1762 - global $current_user;
1537 + public function getBackupTaskById( $id ) {
1538 + return $this->wpdb->get_row( 'SELECT * FROM ' . $this->tableName( 'wp_backup' ) . ' WHERE id= ' . $id );
1539 + }
1763 1540
1764 - $userid = $current_user->ID;
1765 - }
1541 + public function getBackupTasksForUser( $orderBy = 'name' ) {
1542 + if ( MainWP_System::Instance()->isSingleUser() ) {
1543 + return $this->getBackupTasks( null, $orderBy );
1544 + }
1766 1545
1767 - $sql = 'SELECT wp.*,wp_sync.*,wp_optionview.* FROM ' . $this->table_name( 'wp' ) . ' wp
1768 - INNER JOIN ' . $this->table_name( 'wp_group' ) . ' wpgroup ON wp.id = wpgroup.wpid
1769 - JOIN ' . $this->table_name( 'group' ) . ' g ON wpgroup.groupid = g.id
1770 - JOIN ' . $this->table_name( 'wp_sync' ) . ' wp_sync ON wp.id = wp_sync.wpid
1771 - JOIN ' . $this->get_option_view() . ' wp_optionview ON wp.id = wp_optionview.wpid
1772 - WHERE g.name="' . $this->escape( $groupname ) . '"';
1773 - if ( null !== $userid ) {
1774 - $sql .= ' AND g.userid = "' . intval( $userid ) . '"';
1775 - }
1546 + global $current_user;
1776 1547
1777 - return $sql;
1778 - }
1548 + return $this->getBackupTasks( $current_user->ID, $orderBy );
1549 + }
1779 1550
1780 - /**
1781 - * Get child site IP address.
1782 - *
1783 - * @param int $wpid Child site ID.
1784 - *
1785 - * @return string|null Child site IP address or null on failure.
1786 - */
1787 - public function get_wp_ip( $wpid ) {
1788 - return $this->wpdb->get_var( $this->wpdb->prepare( 'SELECT ip FROM ' . $this->table_name( 'request_log' ) . ' WHERE wpid = %d', $wpid ) );
1789 - }
1551 + public function getBackupTasks( $userid = null, $orderBy = null ) {
1552 + return $this->wpdb->get_results( 'SELECT * FROM ' . $this->tableName( 'wp_backup' ) . ' WHERE ' . ( $userid == null ? '' : 'userid= ' . $userid . ' AND ' ) . ' template = 0 ' . ( $orderBy != null ? 'ORDER BY ' . $orderBy : '' ), OBJECT );
1553 + }
1790 1554
1791 - /**
1792 - * Add website to the MainWP Dashboard.
1793 - *
1794 - * @param int $userid Current user ID.
1795 - * @param string $name Child site name.
1796 - * @param string $url Child site URL.
1797 - * @param string $admin Child site administrator username.
1798 - * @param string $pubkey OpenSSL public key.
1799 - * @param string $privkey OpenSSL private key.
1800 - * @param array $params Other params.
1801 - *
1802 - * @return int|false Child site ID or false on failure.
1803 - *
1804 - * @uses \MainWP\Dashboard\MainWP_Utility::ctype_digit()
1805 - */
1806 - public function add_website( // phpcs:ignore -- NOSONAR - complex.
1807 - $userid,
1808 - $name,
1809 - $url,
1810 - $admin,
1811 - $pubkey,
1812 - $privkey,
1813 - $params = array()
1814 - ) {
1555 + public function addBackupTask( $userid, $name, $schedule, $type, $exclude, $sites, $groups, $subfolder, $filename,
1556 + $template, $excludebackup, $excludecache, $excludenonwp, $excludezip, $archiveFormat,
1557 + $maximumFileDescriptorsOverride, $maximumFileDescriptorsAuto, $maximumFileDescriptors, $loadFilesBeforeZip ) {
1558 + if ( MainWP_Utility::ctype_digit( $userid ) ) {
1559 + $values = array(
1560 + 'userid' => $userid,
1561 + 'name' => $name,
1562 + 'schedule' => $schedule,
1563 + 'type' => $type,
1564 + 'exclude' => $exclude,
1565 + 'sites' => $sites,
1566 + 'groups' => $groups,
1567 + 'last' => 0,
1568 + 'last_run' => 0,
1569 + 'last_run_manually' => 0,
1570 + 'completed_sites' => '',
1571 + 'completed' => 0,
1572 + 'backup_errors' => '',
1573 + 'subfolder' => MainWP_Utility::removePreSlashSpaces( $subfolder ),
1574 + 'filename' => $filename,
1575 + 'paused' => 0,
1576 + 'template' => $template,
1577 + 'excludebackup' => $excludebackup,
1578 + 'excludecache' => $excludecache,
1579 + 'excludenonwp' => $excludenonwp,
1580 + 'excludezip' => $excludezip,
1581 + 'archiveFormat' => $archiveFormat,
1582 + 'loadFilesBeforeZip' => $loadFilesBeforeZip,
1583 + 'maximumFileDescriptorsOverride' => $maximumFileDescriptorsOverride,
1584 + 'maximumFileDescriptorsAuto' => $maximumFileDescriptorsAuto,
1585 + 'maximumFileDescriptors' => $maximumFileDescriptors,
1586 + );
1815 1587
1816 - if ( ! is_array( $params ) ) {
1817 - $params = array();
1818 - }
1588 + if ( $this->wpdb->insert( $this->tableName( 'wp_backup' ), $values ) ) {
1589 + return $this->getBackupTaskById( $this->wpdb->insert_id );
1590 + }
1591 + }
1819 1592
1820 - $groupids = isset( $params['groupids'] ) ? $params['groupids'] : array();
1821 - $groupnames = isset( $params['groupnames'] ) ? $params['groupnames'] : array();
1822 - $verifyCertificate = isset( $params['verifyCertificate'] ) ? (int) $params['verifyCertificate'] : 1;
1823 - $uniqueId = isset( $params['uniqueId'] ) ? $params['uniqueId'] : '';
1824 - $http_user = isset( $params['http_user'] ) ? $params['http_user'] : null;
1825 - $http_pass = isset( $params['http_pass'] ) ? $params['http_pass'] : null;
1826 - $sslVersion = isset( $params['sslVersion'] ) ? $params['sslVersion'] : 0;
1827 - $wpe = isset( $params['wpe'] ) ? $params['wpe'] : 0;
1828 - $isStaging = isset( $params['isStaging'] ) ? $params['isStaging'] : 0;
1593 + return false;
1594 + }
1829 1595
1830 - if ( MainWP_Utility::ctype_digit( $userid ) ) {
1831 - if ( '/' !== substr( $url, - 1 ) ) {
1832 - $url .= '/';
1833 - }
1834 - $values = array(
1835 - 'userid' => $userid,
1836 - 'adminname' => $this->escape( $admin ),
1837 - 'name' => $this->escape( wp_strip_all_tags( $name ) ),
1838 - 'url' => $this->escape( $url ),
1839 - 'pubkey' => $this->escape( $pubkey ),
1840 - 'privkey' => $this->escape( $privkey ),
1841 - 'siteurl' => '',
1842 - 'ga_id' => '',
1843 - 'gas_id' => 0,
1844 - 'offline_checks_last' => 0,
1845 - 'offline_check_result' => 0,
1846 - 'note' => '',
1847 - 'statsUpdate' => 0,
1848 - 'directories' => '',
1849 - 'plugin_upgrades' => '',
1850 - 'theme_upgrades' => '',
1851 - 'translation_upgrades' => '',
1852 - 'securityIssues' => '',
1853 - 'themes' => '',
1854 - 'ignored_themes' => '',
1855 - 'plugins' => '',
1856 - 'ignored_plugins' => '',
1857 - 'users' => '',
1858 - 'categories' => '',
1859 - 'pluginDir' => '',
1860 - 'automatic_update' => 0,
1861 - 'backup_before_upgrade' => 2,
1862 - 'verify_certificate' => intval( $verifyCertificate ),
1863 - 'ssl_version' => $sslVersion,
1864 - 'uniqueId' => $uniqueId,
1865 - 'mainwpdir' => 0,
1866 - 'http_user' => $http_user,
1867 - 'http_pass' => $http_pass,
1868 - 'wpe' => $wpe,
1869 - 'is_staging' => $isStaging,
1870 - );
1596 + public function updateBackupTask( $id, $userid, $name, $schedule, $type, $exclude, $sites, $groups, $subfolder,
1597 + $filename, $excludebackup, $excludecache, $excludenonwp, $excludezip, $archiveFormat,
1598 + $maximumFileDescriptorsOverride, $maximumFileDescriptorsAuto, $maximumFileDescriptors, $loadFilesBeforeZip ) {
1599 + if ( MainWP_Utility::ctype_digit( $userid ) && MainWP_Utility::ctype_digit( $id ) ) {
1600 + return $this->wpdb->update( $this->tableName( 'wp_backup' ), array(
1601 + 'userid' => $userid,
1602 + 'name' => $name,
1603 + 'schedule' => $schedule,
1604 + 'type' => $type,
1605 + 'exclude' => $exclude,
1606 + 'sites' => $sites,
1607 + 'groups' => $groups,
1608 + 'subfolder' => MainWP_Utility::removePreSlashSpaces( $subfolder ),
1609 + 'filename' => $filename,
1610 + 'excludebackup' => $excludebackup,
1611 + 'excludecache' => $excludecache,
1612 + 'excludenonwp' => $excludenonwp,
1613 + 'excludezip' => $excludezip,
1614 + 'archiveFormat' => $archiveFormat,
1615 + 'loadFilesBeforeZip' => $loadFilesBeforeZip,
1616 + 'maximumFileDescriptorsOverride' => $maximumFileDescriptorsOverride,
1617 + 'maximumFileDescriptorsAuto' => $maximumFileDescriptorsAuto,
1618 + 'maximumFileDescriptors' => $maximumFileDescriptors,
1619 + ), array( 'id' => $id ) );
1620 + }
1871 1621
1872 - $syncValues = array(
1873 - 'dtsSync' => 0,
1874 - 'dtsSyncStart' => 0,
1875 - 'dtsAutomaticSync' => 0,
1876 - 'dtsAutomaticSyncStart' => 0,
1877 - 'totalsize' => 0,
1878 - 'extauth' => '',
1879 - 'sync_errors' => '',
1880 - );
1881 - if ( $this->wpdb->insert( $this->table_name( 'wp' ), $values ) ) {
1882 - $websiteid = $this->wpdb->insert_id;
1883 - $syncValues['wpid'] = $websiteid;
1884 - $this->wpdb->insert( $this->table_name( 'wp_sync' ), $syncValues );
1885 - $this->wpdb->insert(
1886 - $this->table_name( 'wp_settings_backup' ),
1887 - array(
1888 - 'wpid' => $websiteid,
1889 - 'archiveFormat' => 'global',
1890 - )
1891 - );
1622 + return false;
1623 + }
1892 1624
1893 - foreach ( $groupnames as $groupname ) {
1894 - if ( $this->wpdb->insert(
1895 - $this->table_name( 'group' ),
1896 - array(
1897 - 'userid' => $userid,
1898 - 'name' => $this->escape( htmlspecialchars( $groupname ) ),
1899 - )
1900 - )
1901 - ) {
1902 - $groupids[] = $this->wpdb->insert_id;
1903 - }
1904 - }
1905 - // add groupids.
1906 - foreach ( $groupids as $groupid ) {
1907 - $this->wpdb->insert(
1908 - $this->table_name( 'wp_group' ),
1909 - array(
1910 - 'wpid' => $websiteid,
1911 - 'groupid' => $groupid,
1912 - )
1913 - );
1914 - }
1625 + public function updateBackupTaskWithValues( $id, $values ) {
1626 + if ( !is_array( $values ) ) {
1627 + return false;
1628 + }
1915 1629
1916 - return $websiteid;
1917 - }
1918 - }
1630 + return $this->wpdb->update( $this->tableName( 'wp_backup' ), $values, array( 'id' => $id ) );
1631 + }
1919 1632
1920 - return false;
1921 - }
1633 + public function updateBackupRun( $id ) {
1634 + if ( MainWP_Utility::ctype_digit( $id ) ) {
1635 + return $this->wpdb->update( $this->tableName( 'wp_backup' ), array(
1636 + 'last_run' => time(),
1637 + 'last' => time(),
1638 + 'completed_sites' => json_encode( array() ),
1639 + ), array( 'id' => $id ) );
1640 + }
1922 1641
1923 - /**
1924 - * Remove child site from the MainWP Dashboard.
1925 - *
1926 - * @param int $websiteid Child site ID.
1927 - *
1928 - * @return int|boolean Return child site ID that was removed or false on failure.
1929 - *
1930 - * @uses \MainWP\Dashboard\MainWP_Utility::ctype_digit()
1931 - */
1932 - public function remove_website( $websiteid ) {
1933 - if ( MainWP_Utility::ctype_digit( $websiteid ) ) {
1934 - $nr = $this->wpdb->query( $this->wpdb->prepare( 'DELETE FROM ' . $this->table_name( 'wp' ) . ' WHERE id=%d', $websiteid ) );
1935 - $this->wpdb->query( $this->wpdb->prepare( 'DELETE FROM ' . $this->table_name( 'wp_group' ) . ' WHERE wpid=%d', $websiteid ) );
1936 - $this->wpdb->query( $this->wpdb->prepare( 'DELETE FROM ' . $this->table_name( 'wp_sync' ) . ' WHERE wpid=%d', $websiteid ) );
1937 - $this->wpdb->query( $this->wpdb->prepare( 'DELETE FROM ' . $this->table_name( 'wp_options' ) . ' WHERE wpid=%d', $websiteid ) );
1938 - $this->wpdb->query( $this->wpdb->prepare( 'DELETE FROM ' . $this->table_name( 'wp_status' ) . ' WHERE wpid=%d', $websiteid ) );
1642 + return false;
1643 + }
1939 1644
1940 - return $nr;
1941 - }
1645 + public function updateBackupRunManually( $id ) {
1646 + if ( MainWP_Utility::ctype_digit( $id ) ) {
1647 + return $this->wpdb->update( $this->tableName( 'wp_backup' ), array( 'last_run_manually' => time() ), array( 'id' => $id ) );
1648 + }
1942 1649
1943 - return false;
1944 - }
1650 + return false;
1651 + }
1945 1652
1946 - /**
1947 - * Update child site db values.
1948 - *
1949 - * @param int $websiteid Child site ID.
1950 - * @param array $fields Database fields to update.
1951 - *
1952 - * @return int|boolean The number of rows updated, or false on error.
1953 - */
1954 - public function update_website_values( $websiteid, $fields ) {
1955 - if ( ! empty( $fields ) ) {
1956 - return $this->wpdb->update( $this->table_name( 'wp' ), $fields, array( 'id' => $websiteid ) );
1957 - }
1653 + public function updateBackupCompleted( $id ) {
1654 + if ( MainWP_Utility::ctype_digit( $id ) ) {
1655 + return $this->wpdb->update( $this->tableName( 'wp_backup' ), array( 'completed' => time() ), array( 'id' => $id ) );
1656 + }
1958 1657
1959 - return false;
1960 - }
1658 + return false;
1659 + }
1961 1660
1962 - /**
1963 - * Update child site sync values.
1964 - *
1965 - * @param int $websiteid Child site ID.
1966 - * @param array $fields Database fields to update.
1967 - *
1968 - * @return int|boolean The number of rows updated, or false on error.
1969 - */
1970 - public function update_website_sync_values( $websiteid, $fields ) {
1971 - if ( ! empty( $fields ) ) {
1972 - return $this->wpdb->update( $this->table_name( 'wp_sync' ), $fields, array( 'wpid' => $websiteid ) );
1973 - }
1661 + public function updateBackupErrors( $id, $errors ) {
1662 + if ( MainWP_Utility::ctype_digit( $id ) ) {
1663 + if ( $errors == '' ) {
1664 + return $this->wpdb->update( $this->tableName( 'wp_backup' ), array( 'backup_errors' => '' ), array( 'id' => $id ) );
1665 + } else {
1666 + $task = $this->getBackupTaskById( $id );
1974 1667
1975 - return false;
1976 - }
1668 + return $this->wpdb->update( $this->tableName( 'wp_backup' ), array( 'backup_errors' => $task->backup_errors . $errors ), array( 'id' => $id ) );
1669 + }
1670 + }
1977 1671
1978 - /**
1979 - * Update child site.
1980 - *
1981 - * @param int $websiteid Website ID.
1982 - * @param string $url Child site URL.
1983 - * @param int $userid Current user ID.
1984 - * @param string $name Child site name.
1985 - * @param string $siteadmin Child site administrator username.
1986 - * @param array $groupids Group IDs.
1987 - * @param array $groupnames Group Names.
1988 - * @param string $pluginDir Plugin directory.
1989 - * @param mixed $maximumFileDescriptorsOverride Overwrite the Maximum File Descriptors option.
1990 - * @param mixed $maximumFileDescriptorsAuto Auto set the Maximum File Descriptors option.
1991 - * @param mixed $maximumFileDescriptors Set the Maximum File Descriptors option.
1992 - * @param int $verifyCertificate Whether or not to verify SSL Certificate.
1993 - * @param mixed $archiveFormat Backup archive formate.
1994 - * @param string $uniqueId Unique security ID.
1995 - * @param string $http_user HTTP Basic Authentication username.
1996 - * @param string $http_pass HTTP Basic Authentication password.
1997 - * @param int $sslVersion SSL Version.
1998 - * @param int $disableChecking Wether or not disable sites status checking.
1999 - * @param int $checkInterval Status checking interval.
2000 - * @param bool $disableHealthChecking Disable Site health threshold.
2001 - * @param int $healthThreshold Site health threshold.
2002 - * @param int $wpe Is it WP Engine hosted site.
2003 - *
2004 - * @return boolean ture on success or false on failure.
2005 - *
2006 - * @uses \MainWP\Dashboard\MainWP_System_Utility::can_edit_website()
2007 - * @uses \MainWP\Dashboard\MainWP_Utility::ctype_digit()
2008 - */
2009 - public function update_website( // phpcs:ignore -- NOSONAR - complex.
2010 - $websiteid,
2011 - $url,
2012 - $userid,
2013 - $name,
2014 - $siteadmin,
2015 - $groupids,
2016 - $groupnames,
2017 - $pluginDir,
2018 - $maximumFileDescriptorsOverride,
2019 - $maximumFileDescriptorsAuto,
2020 - $maximumFileDescriptors,
2021 - $verifyCertificate = 1,
2022 - $archiveFormat = 'global',
2023 - $uniqueId = '',
2024 - $http_user = null,
2025 - $http_pass = null,
2026 - $sslVersion = 0,
2027 - $disableChecking = 1,
2028 - $checkInterval = 1440,
2029 - $disableHealthChecking = 1,
2030 - $healthThreshold = 80,
2031 - $wpe = 0
2032 - ) {
1672 + return false;
1673 + }
2033 1674
2034 - if ( MainWP_Utility::ctype_digit( $websiteid ) && MainWP_Utility::ctype_digit( $userid ) ) {
2035 - $website = $this->get_website_by_id( $websiteid );
2036 - if ( MainWP_System_Utility::can_edit_website( $website ) ) {
2037 - // update admin.
2038 - $this->wpdb->query( $this->wpdb->prepare( 'UPDATE ' . $this->table_name( 'wp' ) . ' SET url="' . $this->escape( $url ) . '", name="' . $this->escape( wp_strip_all_tags( $name ) ) . '", adminname="' . $this->escape( $siteadmin ) . '",pluginDir="' . $this->escape( $pluginDir ) . '", verify_certificate="' . intval( $verifyCertificate ) . '", ssl_version="' . intval( $sslVersion ) . '", wpe="' . intval( $wpe ) . '", uniqueId="' . $this->escape( $uniqueId ) . '", http_user="' . $this->escape( $http_user ) . '", http_pass="' . $this->escape( $http_pass ) . '", disable_status_check="' . $this->escape( $disableChecking ) . '", status_check_interval="' . $this->escape( $checkInterval ) . '", disable_health_check="' . $this->escape( $disableHealthChecking ) . '", health_threshold="' . $this->escape( $healthThreshold ) . '" WHERE id=%d', $websiteid ) );
2039 - $this->wpdb->query( $this->wpdb->prepare( 'UPDATE ' . $this->table_name( 'wp_settings_backup' ) . ' SET archiveFormat = "' . $this->escape( $archiveFormat ) . '" WHERE wpid=%d', $websiteid ) );
1675 + public function updateCompletedSites( $id, $completedSites ) {
1676 + if ( MainWP_Utility::ctype_digit( $id ) ) {
1677 + return $this->wpdb->update( $this->tableName( 'wp_backup' ), array( 'completed_sites' => json_encode( $completedSites ) ), array( 'id' => $id ) );
1678 + }
2040 1679
2041 - if ( get_option( 'mainwp_enableLegacyBackupFeature' ) ) {
2042 - $this->wpdb->query( $this->wpdb->prepare( 'UPDATE ' . $this->table_name( 'wp' ) . ' SET maximumFileDescriptorsOverride = ' . ( $maximumFileDescriptorsOverride ? 1 : 0 ) . ',maximumFileDescriptorsAuto= ' . ( $maximumFileDescriptorsAuto ? 1 : 0 ) . ',maximumFileDescriptors = ' . $maximumFileDescriptors . ' WHERE id=%d', $websiteid ) );
2043 - }
1680 + return false;
1681 + }
2044 1682
2045 - // remove groups.
2046 - $this->wpdb->query( $this->wpdb->prepare( 'DELETE FROM ' . $this->table_name( 'wp_group' ) . ' WHERE wpid=%d', $websiteid ) );
2047 - // Remove GA stats.
2048 - $showErrors = $this->wpdb->hide_errors();
1683 + public function getOfflineChecks() {
1684 + return $this->wpdb->get_results( 'SELECT * FROM ' . $this->tableName( 'wp' ) . ' WHERE (offline_checks="hourly" AND ' . time() . ' - offline_checks_last >= ' . ( 60 * 60 * 1 ) . ') OR (offline_checks="2xday" AND ' . time() . ' - offline_checks_last >= ' . ( 60 * 60 * 12 * 1 ) . ') OR (offline_checks="daily" AND ' . time() . ' - offline_checks_last >= ' . ( 60 * 60 * 24 * 1 ) . ') OR (offline_checks="weekly" AND ' . time() . ' - offline_checks_last >= ' . ( 60 * 60 * 24 * 7 ) . ')', OBJECT );
1685 + }
2049 1686
2050 - /**
2051 - * Action: mainwp_ga_delete_site
2052 - *
2053 - * Fires upon site removal process in order to delete Google Analytics data.
2054 - *
2055 - * @param int $websiteid Child site ID.
2056 - *
2057 - * @since Unknown
2058 - */
2059 - do_action( 'mainwp_ga_delete_site', $websiteid );
1687 + public function getWebsitesCheckUpdatesCount() {
1688 + $where = $this->getWhereAllowAccessSites( 'wp' );
2060 1689
2061 - if ( $showErrors ) {
2062 - $this->wpdb->show_errors();
2063 - }
2064 - // add groups with groupnames.
2065 - foreach ( $groupnames as $groupname ) {
2066 - if ( $this->wpdb->insert(
2067 - $this->table_name( 'group' ),
2068 - array(
2069 - 'userid' => $userid,
2070 - 'name' => $this->escape( $groupname ),
2071 - )
2072 - )
2073 - ) {
2074 - $groupids[] = $this->wpdb->insert_id;
2075 - }
2076 - }
2077 - // add groupids.
2078 - foreach ( $groupids as $groupid ) {
2079 - $this->wpdb->insert(
2080 - $this->table_name( 'wp_group' ),
2081 - array(
2082 - 'wpid' => $websiteid,
2083 - 'groupid' => $groupid,
2084 - )
2085 - );
2086 - }
1690 + return $this->wpdb->get_var( 'SELECT count(wp.id) FROM ' . $this->tableName( 'wp' ) . ' wp
1691 + JOIN ' . $this->tableName( 'wp_sync' ) . ' wp_sync ON wp.id = wp_sync.wpid
1692 + WHERE (wp_sync.dtsAutomaticSyncStart = 0 OR DATE(FROM_UNIXTIME(wp_sync.dtsAutomaticSyncStart)) <> DATE(NOW())) ' . $where );
1693 + }
2087 1694
2088 - return true;
2089 - }
2090 - }
1695 + public function getWebsitesCountWhereDtsAutomaticSyncSmallerThenStart() {
1696 + $where = $this->getWhereAllowAccessSites( 'wp' );
2091 1697
2092 - return false;
2093 - }
1698 + //once a day
1699 + return $this->wpdb->get_var( 'SELECT count(wp.id) FROM ' . $this->tableName( 'wp' ) . ' wp
1700 + JOIN ' . $this->tableName( 'wp_sync' ) . ' wp_sync ON wp.id = wp_sync.wpid
1701 + WHERE ((wp_sync.dtsAutomaticSync < wp_sync.dtsAutomaticSyncStart) OR (wp_sync.dtsAutomaticSyncStart = 0) OR (DATE(FROM_UNIXTIME(wp_sync.dtsAutomaticSyncStart)) <> DATE(NOW()))) ' . $where );
1702 + }
2094 1703
2095 - /**
2096 - * Get websites check updates count.
2097 - *
2098 - * @param int $lasttime_start Lasttime start automatic update.
2099 - *
2100 - * @return int Child sites update count.
2101 - */
2102 - public function get_websites_check_updates_count( $lasttime_start ) {
2103 - $where = $this->get_sql_where_allow_access_sites( 'wp' );
1704 + public function getWebsitesLastAutomaticSync() {
1705 + //once a day
1706 + return $this->wpdb->get_var( 'SELECT MAX(wp_sync.dtsAutomaticSync) FROM ' . $this->tableName( 'wp' ) . ' wp
1707 + JOIN ' . $this->tableName( 'wp_sync' ) . ' wp_sync ON wp.id = wp_sync.wpid' );
1708 + }
2104 1709
2105 - return $this->wpdb->get_var( 'SELECT count(wp.id) FROM ' . $this->table_name( 'wp' ) . ' wp JOIN ' . $this->table_name( 'wp_sync' ) . ' wp_sync ON wp.id = wp_sync.wpid WHERE ( wp_sync.dtsAutomaticSyncStart = 0 OR wp_sync.dtsAutomaticSyncStart < ' . intval( $lasttime_start ) . ')' . $where );
2106 - }
1710 + public function getWebsitesCheckUpdates( $limit ) {
1711 + $where = $this->getWhereAllowAccessSites( 'wp' );
2107 1712
2108 - /**
2109 - * Get child site count where date & time Session sync is smaller then start.
2110 - *
2111 - * @param int $lasttime_start Last time start automatic.
2112 - *
2113 - * @return int Returned child site count.
2114 - */
2115 - public function get_websites_count_where_dts_automatic_sync_smaller_then_start( $lasttime_start ) {
2116 - $where = $this->get_sql_where_allow_access_sites( 'wp' );
1713 + //once a day
1714 + return $this->wpdb->get_results( 'SELECT wp.*,wp_sync.*,wp_optionview.*
1715 + FROM ' . $this->tableName( 'wp' ) . ' wp
1716 + JOIN ' . $this->tableName( 'wp_sync' ) . ' wp_sync ON wp.id = wp_sync.wpid
1717 + JOIN ' . $this->getOptionView() . ' wp_optionview ON wp.id = wp_optionview.wpid
1718 + WHERE (wp_sync.dtsAutomaticSyncStart = 0 OR DATE(FROM_UNIXTIME(wp_sync.dtsAutomaticSyncStart)) <> DATE(NOW())) ' . $where . ' LIMIT 0,' . $limit, OBJECT );
1719 + }
2117 1720
2118 - return $this->wpdb->get_var( 'SELECT count(wp.id) FROM ' . $this->table_name( 'wp' ) . ' wp JOIN ' . $this->table_name( 'wp_sync' ) . ' wp_sync ON wp.id = wp_sync.wpid WHERE (( wp_sync.dtsAutomaticSync < wp_sync.dtsAutomaticSyncStart AND wp_sync.dtsAutomaticSyncStart > ' . intval( $lasttime_start ) . ') OR (wp_sync.dtsAutomaticSyncStart = 0)) ' . $where );
2119 - }
1721 + public function getWebsitesStatsUpdateSQL() {
1722 + $where = $this->getWhereAllowAccessSites();
2120 1723
2121 - /**
2122 - * Get child site last automatic sync date & time.
2123 - *
2124 - * @return string Date and time of last automatic sync.
2125 - */
2126 - public function get_websites_last_automatic_sync() {
2127 - return $this->wpdb->get_var( 'SELECT MAX(wp_sync.dtsAutomaticSync) FROM ' . $this->table_name( 'wp' ) . ' wp JOIN ' . $this->table_name( 'wp_sync' ) . ' wp_sync ON wp.id = wp_sync.wpid' );
2128 - }
1724 + //once a week
1725 + return 'SELECT * FROM ' . $this->tableName( 'wp' ) . ' WHERE (statsUpdate = 0 OR ' . time() . ' - statsUpdate >= ' . ( 60 * 60 * 24 * 7 ) . ')' . $where . ' ORDER BY statsUpdate ASC';
1726 + }
2129 1727
2130 - /**
2131 - * Get child sites check updates.
2132 - *
2133 - * @param int $limit Query limit.
2134 - * @param int $lasttime_start Lasttime start automatic update.
2135 - *
2136 - * @return object|null Database query result or null on failure.
2137 - */
2138 - public function get_websites_check_updates( $limit, $lasttime_start ) {
2139 - $where = $this->get_sql_where_allow_access_sites( 'wp' );
1728 + public function updateWebsiteStats( $websiteid, $statsUpdated ) {
1729 + return $this->wpdb->update( $this->tableName( 'wp' ), array(
1730 + 'statsUpdate' => $statsUpdated,
1731 + ), array( 'id' => $websiteid ) );
1732 + }
2140 1733
2141 - return $this->wpdb->get_results( 'SELECT wp.*,wp_sync.*,wp_optionview.* FROM ' . $this->table_name( 'wp' ) . ' wp JOIN ' . $this->table_name( 'wp_sync' ) . ' wp_sync ON wp.id = wp_sync.wpid JOIN ' . $this->get_option_view() . ' wp_optionview ON wp.id = wp_optionview.wpid WHERE ( wp_sync.dtsAutomaticSync = 0 OR wp_sync.dtsAutomaticSyncStart = 0 OR wp_sync.dtsAutomaticSyncStart < ' . intval( $lasttime_start ) . ' ) ' . $where . ' ORDER BY wp_sync.dtsAutomaticSyncStart ASC LIMIT ' . $limit, OBJECT );
2142 - }
1734 + public function getBackupTasksToComplete() {
1735 + return $this->wpdb->get_results( 'SELECT * FROM ' . $this->tableName( 'wp_backup' ) . ' WHERE paused = 0 AND completed < last_run'//AND '. time() . ' - last_run >= 120 AND ' . time() . ' - last >= 120'
1736 + , OBJECT );
1737 + }
2143 1738
2144 - /**
2145 - * Get website update stats via SQL.
2146 - *
2147 - * @return object|null Database query result of null on failure.
2148 - */
2149 - public function get_websites_stats_update_sql() {
2150 - $where = $this->get_sql_where_allow_access_sites( 'wp' );
2151 - return 'SELECT wp.*,wp_sync.sync_errors FROM ' . $this->table_name( 'wp' ) . ' wp JOIN ' . $this->table_name( 'wp_sync' ) . ' wp_sync ON wp.id = wp_sync.wpid WHERE (wp.statsUpdate = 0 OR ' . time() . ' - wp.statsUpdate >= ' . ( 60 * 60 * 24 ) . ')' . $where . ' ORDER BY wp.statsUpdate ASC';
2152 - }
1739 + public function getBackupTasksTodoDaily() {
1740 + return $this->wpdb->get_results( 'SELECT * FROM ' . $this->tableName( 'wp_backup' ) . ' WHERE paused = 0 AND schedule="daily" AND ' . time() . ' - last_run >= ' . ( 60 * 60 * 24 ), OBJECT );
1741 + }
2153 1742
2154 - /**
2155 - * Update child site statistics.
2156 - *
2157 - * Update whether or not a child site has been updated.
2158 - *
2159 - * @param mixed $websiteid Child site ID.
2160 - * @param mixed $statsUpdated Child site Update status.
2161 - *
2162 - * @return (int|boolean) Number of rows effected in update or false on failure.
2163 - */
2164 - public function update_website_stats( $websiteid, $statsUpdated ) {
2165 - return $this->wpdb->update(
2166 - $this->table_name( 'wp' ),
2167 - array( 'statsUpdate' => $statsUpdated ),
2168 - array( 'id' => $websiteid )
2169 - );
2170 - }
1743 + public function getBackupTasksTodoWeekly() {
1744 + return $this->wpdb->get_results( 'SELECT * FROM ' . $this->tableName( 'wp_backup' ) . ' WHERE paused = 0 AND schedule="weekly" AND ' . time() . ' - last_run >= ' . ( 60 * 60 * 24 * 7 ), OBJECT );
1745 + }
2171 1746
2172 - /**
2173 - * Get child site by url.
2174 - *
2175 - * @param string $url Child site URL.
2176 - *
2177 - * @return object|null Database query result or null on failure.
2178 - */
2179 - public function get_websites_by_url( $url ) {
2180 - if ( '/' !== substr( $url, - 1 ) ) {
2181 - $url .= '/';
2182 - }
2183 - $results = $this->wpdb->get_results( $this->wpdb->prepare( 'SELECT * FROM ' . $this->table_name( 'wp' ) . ' wp JOIN ' . $this->table_name( 'wp_sync' ) . ' wp_sync ON wp.id = wp_sync.wpid WHERE wp.url = %s ', $this->escape( $url ) ), OBJECT );
2184 - if ( $results ) {
2185 - return $results;
2186 - }
1747 + public function getBackupTasksTodoMonthly() {
1748 + return $this->wpdb->get_results( 'SELECT * FROM ' . $this->tableName( 'wp_backup' ) . ' WHERE paused = 0 AND schedule="monthly" AND ' . time() . ' - last_run >= ' . ( 60 * 60 * 24 * 30 ), OBJECT );
1749 + }
2187 1750
2188 - if ( stristr( $url, '/www.' ) ) {
2189 - // remove www if it's there!
2190 - $url = str_replace( '/www.', '/', $url );
2191 - } else {
2192 - // add www if it's not there!
2193 - $url = str_replace( 'https://', 'https://www.', $url );
2194 - $url = str_replace( 'http://', 'http://www.', $url );
2195 - }
1751 + public function getUserNotificationEmail( $userid ) {
1752 + $theUserId = $userid;
1753 + if ( MainWP_System::Instance()->isSingleUser() ) {
1754 + $theUserId = 0;
1755 + }
1756 + $user_email = $this->wpdb->get_var( 'SELECT user_email FROM ' . $this->tableName( 'users' ) . ' WHERE userid = ' . $theUserId );
2196 1757
2197 - $results = $this->wpdb->get_results( $this->wpdb->prepare( 'SELECT * FROM ' . $this->table_name( 'wp' ) . ' wp JOIN ' . $this->table_name( 'wp_sync' ) . ' wp_sync ON wp.id = wp_sync.wpid WHERE wp.url = %s ', $this->escape( $url ) ), OBJECT );
2198 - if ( $results ) {
2199 - return $results;
2200 - }
1758 + if ( $user_email == null || $user_email == '' ) {
1759 + $user_email = $this->wpdb->get_var( 'SELECT user_email FROM ' . $this->wpdb->prefix . 'users WHERE id = ' . $userid );
1760 + }
2201 1761
2202 - $url = str_replace( array( 'https://www.', 'http://www.', 'https://', 'http://', 'www.' ), array( '', '', '', '', '' ), $url );
1762 + return $user_email;
1763 + }
2203 1764
2204 - return $this->wpdb->get_results( $this->wpdb->prepare( 'SELECT * FROM ' . $this->table_name( 'wp' ) . ' wp JOIN ' . $this->table_name( 'wp_sync' ) . " wp_sync ON wp.id = wp_sync.wpid WHERE replace(replace(replace(replace(replace(wp.url, 'https://www.',''), 'http://www.',''), 'https://', ''), 'http://', ''), 'www.', '') = %s ", $this->escape( $url ) ), OBJECT );
2205 - }
1765 + public function getUserExtension() {
1766 + global $current_user;
2206 1767
2207 - /**
2208 - * Get websites offline status.
2209 - *
2210 - * @return array Child site monitoring status.
2211 - */
2212 - public function get_websites_offline_status_to_send_notice() {
2213 - $where = $this->get_sql_where_allow_access_sites( 'wp' );
2214 - $extra_view = array( 'monitoring_notification_emails', 'settings_notification_emails' );
1768 + if ( empty( $current_user ) ) {
1769 + if ( MainWP_System::Instance()->isSingleUser() ) {
1770 + $userid = 0;
1771 + } else {
1772 + return false;
1773 + }
1774 + } else {
1775 + $userid = $current_user->ID;
1776 + }
2215 1777
2216 - return $this->wpdb->get_results(
2217 - 'SELECT wp.*,wp_sync.*,wp_optionview.* FROM ' . $this->table_name( 'wp' ) . ' wp
2218 - JOIN ' . $this->table_name( 'wp_sync' ) . ' wp_sync ON wp.id = wp_sync.wpid
2219 - JOIN ' . $this->get_option_view( $extra_view ) . ' wp_optionview ON wp.id = wp_optionview.wpid
2220 - WHERE wp.disable_status_check <> 1 AND wp.offline_check_result <> 1 AND wp.offline_check_result <> 0 AND wp.http_code_noticed = 0' . // http_code_noticed = 0: not noticed yet.
2221 - $where,
2222 - OBJECT
2223 - );
2224 - }
1778 + return $this->getUserExtensionByUserId( $userid );
1779 + }
2225 1780
2226 - /**
2227 - * Method get_websites_to_notice_health_threshold()
2228 - *
2229 - * Get websites to notice site health.
2230 - *
2231 - * @param int $globalThreshold Global site health threshold.
2232 - */
2233 - public function get_websites_to_notice_health_threshold( $globalThreshold ) {
1781 + public function getUserExtensionByUserId( $userid ) {
1782 + if ( MainWP_System::Instance()->isSingleUser() ) {
1783 + $userid = 0;
1784 + }
2234 1785
2235 - $where = $this->get_sql_where_allow_access_sites( 'wp' );
2236 - $extra_view = array( 'monitoring_notification_emails', 'settings_notification_emails' );
1786 + $row = $this->wpdb->get_row( 'SELECT * FROM ' . $this->tableName( 'users' ) . ' WHERE userid= ' . $userid, OBJECT );
1787 + if ( $row == null ) {
1788 + $this->createUserExtension( $userid );
1789 + $row = $this->wpdb->get_row( 'SELECT * FROM ' . $this->tableName( 'users' ) . ' WHERE userid= ' . $userid, OBJECT );
1790 + }
2237 1791
2238 - if ( 80 >= $globalThreshold ) { // actual is 80.
2239 - // should-be-improved site health.
2240 - $where_global_threshold = '( wp.health_threshold = 0 AND wp_sync.health_value < 80 )';
2241 - } else {
2242 - // good site health.
2243 - $where_global_threshold = '( wp.health_threshold = 0 AND wp_sync.health_value >= 80 )';
2244 - }
1792 + return $row;
1793 + }
2245 1794
2246 - $where_site_threshold = ' ( wp.health_threshold = 80 AND wp_sync.health_value < 80 ) '; // should-be-improved site health.
2247 - $where_site_threshold .= ' OR ( wp.health_threshold = 100 AND wp_sync.health_value >= 80 ) '; // good site health.
1795 + protected function createUserExtension( $userId ) {
1796 + $fields = array(
1797 + 'userid' => $userId,
1798 + 'user_email' => '',
1799 + 'ignored_plugins' => '',
1800 + 'trusted_plugins' => '',
1801 + 'trusted_plugins_notes' => '',
1802 + 'ignored_themes' => '',
1803 + 'trusted_themes' => '',
1804 + 'trusted_themes_notes' => '',
1805 + 'pluginDir' => ''
1806 + );
2248 1807
2249 - return $this->wpdb->get_results(
2250 - 'SELECT wp.*,wp_sync.*,wp_optionview.* FROM ' . $this->table_name( 'wp' ) . ' wp
2251 - JOIN ' . $this->table_name( 'wp_sync' ) . ' wp_sync ON wp.id = wp_sync.wpid
2252 - JOIN ' . $this->get_option_view( $extra_view ) . ' wp_optionview ON wp.id = wp_optionview.wpid
2253 - WHERE wp.disable_health_check <> 1 AND wp.offline_check_result = 1 AND ( ' . $where_global_threshold . ' OR' . $where_site_threshold . ' ) AND wp_sync.health_site_noticed = 0 ' .
2254 - $where,
2255 - OBJECT
2256 - );
2257 - }
1808 + $this->wpdb->insert( $this->tableName( 'users' ), $fields );
1809 + }
2258 1810
2259 - /**
2260 - * Get websites offline status.
2261 - *
2262 - * @return array Sites with offline status.
2263 - */
2264 - public function get_websites_offline_check_status() {
2265 - $where = $this->get_sql_where_allow_access_sites( 'wp' );
2266 - $extra_view = array( 'settings_notification_emails' );
1811 + public function updateUserExtension( $userExtension ) {
2267 1812
2268 - return $this->wpdb->get_results(
2269 - 'SELECT wp.*,wp_optionview.* FROM ' . $this->table_name( 'wp' ) . ' wp
2270 - JOIN ' . $this->get_option_view( $extra_view ) . ' wp_optionview ON wp.id = wp_optionview.wpid
2271 - WHERE wp.disable_status_check <> 1 AND wp.offline_check_result = -1' . // offline checked status.
2272 - $where,
2273 - OBJECT
2274 - );
2275 - }
1813 + if (is_object($userExtension)) {
1814 + $userid = $userExtension->userid;
1815 + } else if (is_array($userExtension)) {
1816 + $userid = $userExtension['userid']; // fix for some
1817 + } else {
1818 + $userid = null;
1819 + }
2276 1820
2277 - /**
2278 - * Get DB Sites.
2279 - *
2280 - * @since 4.6
2281 - *
2282 - * @param mixed $params params.
2283 - *
2284 - * @return array $dbwebsites.
2285 - */
2286 - public static function get_db_sites( $params = array() ) { // phpcs:ignore -- NOSONAR - complex.
1821 + if ( $userid == null ) {
1822 + if ( MainWP_System::Instance()->isSingleUser() ) {
1823 + $userid = '0';
1824 + } else {
1825 + global $current_user;
1826 + $userid = $current_user->ID;
1827 + }
1828 + }
1829 + $row = $this->wpdb->get_row( 'SELECT * FROM ' . $this->tableName( 'users' ) . ' WHERE userid= ' . $userid, OBJECT );
1830 + if ( $row == null ) {
1831 + $this->createUserExtension( $userid );
1832 + }
2287 1833
2288 - $dbwebsites = array();
1834 + $fields = array();
1835 + foreach ( $userExtension as $field => $value ) {
1836 + if ( $value != $row->$field ) {
1837 + $fields[ $field ] = $value;
1838 + }
1839 + }
2289 1840
2290 - $data_fields = MainWP_System_Utility::get_default_map_site_fields();
2291 - $data_fields[] = 'verify_certificate';
2292 - $data_fields[] = 'client_id';
1841 + if ( count( $fields ) > 0 ) {
1842 + $this->wpdb->update( $this->tableName( 'users' ), $fields, array( 'userid' => $userid ) );
1843 + }
2293 1844
2294 - $fields = isset( $params['fields'] ) && is_array( $params['fields'] ) ? $params['fields'] : array();
2295 - $sites = isset( $params['sites'] ) && is_array( $params['sites'] ) ? $params['sites'] : array();
2296 - $groups = isset( $params['groups'] ) && is_array( $params['groups'] ) ? $params['groups'] : array();
2297 - $clients = isset( $params['clients'] ) && is_array( $params['clients'] ) ? $params['clients'] : array();
1845 + $row = $this->wpdb->get_row( 'SELECT * FROM ' . $this->tableName( 'users' ) . ' WHERE userid= ' . $userid, OBJECT );
2298 1846
2299 - if ( is_array( $fields ) ) {
2300 - foreach ( $fields as $field_indx => $field_name ) {
1847 + return $row;
1848 + }
2301 1849
2302 - $get_field = $field_name;
2303 - if ( is_numeric( $get_field ) || is_bool( $get_field ) ) { // to compatible fix.
2304 - $get_field = $field_indx;
2305 - }
1850 + public function getTips() {
1851 + return $this->wpdb->get_results( 'SELECT * FROM ' . $this->tableName( 'tips' ) . ' ORDER BY seq ASC', OBJECT );
1852 + }
2306 1853
2307 - if ( in_array( $get_field, static::$possible_options ) && ! in_array( $get_field, $data_fields ) ) {
2308 - $data_fields[] = $get_field;
2309 - }
2310 - }
2311 - }
1854 + public function addTip( $tip_seq, $tip_content ) {
1855 + return $this->wpdb->insert( $this->tableName( 'tips' ), array( 'seq' => $tip_seq, 'content' => $tip_content ) );
1856 + }
2312 1857
2313 - if ( ! empty( $sites ) ) {
2314 - foreach ( $sites as $v ) {
2315 - if ( MainWP_Utility::ctype_digit( $v ) ) {
2316 - $website = static::instance()->get_website_by_id( $v );
2317 - if ( empty( $website ) ) {
2318 - continue;
2319 - }
2320 - $dbwebsites[ $website->id ] = MainWP_Utility::map_site( $website, $data_fields );
2321 - }
2322 - }
2323 - }
1858 + public function updateTip( $tip_id, $tip_seq, $tip_content ) {
1859 + return $this->wpdb->update( $this->tableName( 'tips' ), array(
1860 + 'seq' => $tip_seq,
1861 + 'content' => $tip_content,
1862 + ), array( 'id' => $tip_id ) );
1863 + }
2324 1864
2325 - if ( ! empty( $groups ) ) {
2326 - foreach ( $groups as $v ) {
2327 - if ( MainWP_Utility::ctype_digit( $v ) ) {
2328 - $websites = static::instance()->query( static::instance()->get_sql_websites_by_group_id( $v ) );
2329 - while ( $websites && ( $website = static::fetch_object( $websites ) ) ) {
2330 - $dbwebsites[ $website->id ] = MainWP_Utility::map_site( $website, $data_fields );
2331 - }
2332 - static::free_result( $websites );
2333 - }
2334 - }
2335 - }
1865 + public function deleteTip( $tip_id ) {
1866 + return $this->wpdb->query( 'DELETE FROM ' . $this->tableName( 'tips' ) . ' WHERE id = ' . $tip_id );
1867 + }
2336 1868
2337 - $params = array(
2338 - 'full_data' => true,
2339 - );
2340 - $client_sites = MainWP_DB_Client::instance()->get_websites_by_client_ids( $clients, $params );
2341 - if ( $client_sites ) {
2342 - foreach ( $client_sites as $website ) {
2343 - $dbwebsites[ $website->id ] = MainWP_Utility::map_site( $website, $data_fields );
2344 - }
2345 - }
2346 - return $dbwebsites;
2347 - }
1869 + public function getMySQLVersion() {
1870 + return $this->wpdb->get_var( 'SHOW VARIABLES LIKE "version"', 1 );
1871 + }
2348 1872
2349 - /**
2350 - * Get Sites.
2351 - *
2352 - * @param int $websiteid The id of the child site you wish to retrieve.
2353 - * @param bool $for_manager Check Team Control.
2354 - * @param array $others Array of others.
2355 - *
2356 - * @return array $output Array of content to output.
2357 - *
2358 - * @uses \MainWP\Dashboard\MainWP_System_Utility::can_edit_website()
2359 - * @uses \MainWP\Dashboard\MainWP_Utility::get_nice_url()
2360 - */
2361 - public function get_sites( $websiteid = null, $for_manager = false, $others = array() ) { // phpcs:ignore -- NOSONAR - not quite complex function.
1873 + public function getRowResult( $sql ) {
1874 + if ( $sql == null ) {
1875 + return null;
1876 + }
2362 1877
2363 - if ( ! is_array( $others ) ) {
2364 - $others = array();
2365 - }
1878 + return $this->wpdb->get_row( $sql, OBJECT );
1879 + }
2366 1880
2367 - $search_site = null;
2368 - $orderBy = 'wp.url';
2369 - $offset = false;
2370 - $rowcount = false;
2371 - $extraWhere = null;
1881 + public function getResultsResult( $sql ) {
1882 + if ( $sql == null ) {
1883 + return null;
1884 + }
2372 1885
2373 - if ( isset( $websiteid ) && ( null !== $websiteid ) ) {
2374 - $website = static::instance()->get_website_by_id( $websiteid );
1886 + return $this->wpdb->get_results( $sql, OBJECT_K );
1887 + }
2375 1888
2376 - if ( ! MainWP_System_Utility::can_edit_website( $website ) ) {
2377 - return false;
2378 - }
1889 + public function query( $sql ) {
1890 + if ( $sql == null ) {
1891 + return false;
1892 + }
2379 1893
2380 - if ( ! mainwp_current_user_have_right( 'site', $websiteid ) ) {
2381 - return false;
2382 - }
1894 + $result = @self::_query( $sql, $this->wpdb->dbh );
2383 1895
2384 - return array(
2385 - array(
2386 - 'id' => $websiteid,
2387 - 'url' => MainWP_Utility::get_nice_url( $website->url, true ),
2388 - 'name' => $website->name,
2389 - 'totalsize' => $website->totalsize,
2390 - 'sync_errors' => $website->sync_errors,
2391 - ),
2392 - );
2393 - } else {
2394 - if ( isset( $others['orderby'] ) ) {
2395 - if ( 'site' === $others['orderby'] ) {
2396 - $orderBy = 'wp.name ' . ( 'asc' === $others['order'] ? 'asc' : 'desc' );
2397 - } elseif ( 'url' === $others['orderby'] ) {
2398 - $orderBy = 'wp.url ' . ( 'asc' === $others['order'] ? 'asc' : 'desc' );
2399 - }
2400 - }
2401 - if ( isset( $others['search'] ) ) {
2402 - $search_site = trim( $others['search'] );
2403 - }
1896 + if ( !$result || ( @MainWP_DB::num_rows( $result ) == 0 ) ) {
1897 + return false;
1898 + }
2404 1899
2405 - if ( is_array( $others ) && isset( $others['plugins_slug'] ) ) {
2406 - $slugs = explode( ',', $others['plugins_slug'] );
2407 - $extraWhere = '';
2408 - foreach ( $slugs as $slug ) {
2409 - $slug = wp_json_encode( $slug );
2410 - $slug = trim( $slug, '"' );
2411 - $slug = str_replace( '\\', '.', $slug );
2412 - $extraWhere .= ' wp.plugins REGEXP "' . $slug . '" OR';
2413 - }
2414 - $extraWhere = trim( rtrim( $extraWhere, 'OR' ) );
1900 + return $result;
1901 + }
2415 1902
2416 - if ( '' === $extraWhere ) {
2417 - $extraWhere = null;
2418 - } else {
2419 - $extraWhere = '(' . $extraWhere . ')';
2420 - }
2421 - }
2422 - }
1903 + protected function escape( $data ) {
1904 + if ( function_exists( 'esc_sql' ) ) {
1905 + return esc_sql( $data );
1906 + } else {
1907 + return $this->wpdb->escape( $data );
1908 + }
1909 + }
2423 1910
2424 - $totalRecords = '';
1911 + //Support old & new versions of wordpress (3.9+)
1912 + public static function use_mysqli() {
1913 + /** @var $this ->wpdb wpdb */
1914 + if ( !function_exists( 'mysqli_connect' ) ) {
1915 + return false;
1916 + }
2425 1917
2426 - if ( isset( $others['per_page'] ) && ! empty( $others['per_page'] ) ) {
2427 - $sql = static::instance()->get_sql_websites_for_current_user( false, $search_site, $orderBy, false, false, $extraWhere, $for_manager );
2428 - $websites_total = static::instance()->query( $sql );
2429 - $totalRecords = ( $websites_total ? static::num_rows( $websites_total ) : 0 );
1918 + return ( self::$instance->wpdb->dbh instanceof mysqli );
1919 + }
2430 1920
2431 - if ( $websites_total ) {
2432 - static::free_result( $websites_total );
2433 - }
1921 + public static function ping( $link ) {
1922 + if ( self::use_mysqli() ) {
1923 + return mysqli_ping( $link );
1924 + } else {
1925 + return mysql_ping( $link );
1926 + }
1927 + }
2434 1928
2435 - $rowcount = absint( $others['per_page'] );
2436 - $pagenum = isset( $others['paged'] ) ? absint( $others['paged'] ) : 0;
2437 - if ( $pagenum > $totalRecords ) {
2438 - $pagenum = $totalRecords;
2439 - }
2440 - $pagenum = max( 1, $pagenum );
2441 - $offset = ( $pagenum - 1 ) * $rowcount;
1929 + public static function _query( $query, $link ) {
1930 + if ( self::use_mysqli() ) {
1931 + return mysqli_query( $link, $query );
1932 + } else {
1933 + return mysql_query( $query, $link );
1934 + }
1935 + }
2442 1936
2443 - }
1937 + public static function fetch_object( $result ) {
1938 + if ( $result === false ) {
1939 + return false;
1940 + }
2444 1941
2445 - $sql = static::instance()->get_sql_websites_for_current_user( false, $search_site, $orderBy, $offset, $rowcount, $extraWhere, $for_manager );
2446 - $websites = static::instance()->query( $sql );
1942 + if ( self::use_mysqli() ) {
1943 + return mysqli_fetch_object( $result );
1944 + } else {
1945 + return mysql_fetch_object( $result );
1946 + }
1947 + }
2447 1948
2448 - $output = array();
2449 - while ( $websites && ( $website = static::fetch_object( $websites ) ) ) {
2450 - $re = array(
2451 - 'id' => $website->id,
2452 - 'url' => MainWP_Utility::get_nice_url( $website->url, true ),
2453 - 'name' => $website->name,
2454 - 'totalsize' => $website->totalsize,
2455 - 'sync_errors' => $website->sync_errors,
2456 - 'client_id' => $website->client_id,
2457 - );
1949 + public static function free_result( $result ) {
1950 + if ( $result === false ) {
1951 + return false;
1952 + }
2458 1953
2459 - if ( 0 < $totalRecords ) {
2460 - $re['totalRecords'] = $totalRecords;
2461 - $totalRecords = 0;
2462 - }
1954 + if ( self::use_mysqli() ) {
1955 + return mysqli_free_result( $result );
1956 + } else {
1957 + return mysql_free_result( $result );
1958 + }
1959 + }
2463 1960
2464 - $output[] = $re;
2465 - }
2466 - static::free_result( $websites );
1961 + public static function data_seek( $result, $offset ) {
1962 + if ( $result === false ) {
1963 + return false;
1964 + }
2467 1965
2468 - return $output;
2469 - }
1966 + if ( self::use_mysqli() ) {
1967 + return mysqli_data_seek( $result, $offset );
1968 + } else {
1969 + return mysql_data_seek( $result, $offset );
1970 + }
1971 + }
2470 1972
2471 - /**
2472 - * Method get_lookup_items().
2473 - *
2474 - * Get bulk lookup items to reduce number of db queries.
2475 - *
2476 - * @param string $item_name lookup item name.
2477 - * @param int $item_id lookup item id.
2478 - * @param string $obj_name loockup object name.
2479 - *
2480 - * @return mixed Result
2481 - */
2482 - public function get_lookup_items( $item_name, $item_id, $obj_name ) {
2483 - return $this->wpdb->get_results( $this->wpdb->prepare( 'SELECT * FROM ' . $this->table_name( 'lookup_item_objects' ) . ' WHERE item_name=%s AND item_id = %d AND object_name = %s', $item_name, $item_id, $obj_name ) ); //phpcs:ignore -- ok.
2484 - }
1973 + public static function fetch_array( $result, $result_type = null ) {
1974 + if ( $result === false ) {
1975 + return false;
1976 + }
2485 1977
2486 - /**
2487 - * Method insert_lookup_item().
2488 - *
2489 - * Insert lookup item, need checks existed before to prevent double values.
2490 - *
2491 - * @param string $item_name item name.
2492 - * @param int $item_id item id.
2493 - * @param string $obj_name object name.
2494 - * @param int $obj_id object id.
2495 - *
2496 - * @return mixed Result
2497 - */
2498 - public function insert_lookup_item( $item_name, $item_id, $obj_name, $obj_id ) {
2499 - if ( empty( $item_name ) || empty( $item_id ) || empty( $obj_name ) || empty( $obj_id ) ) {
2500 - return false;
2501 - }
2502 - $data = array(
2503 - 'item_name' => 'cost',
2504 - 'item_id' => $item_id,
2505 - 'object_name' => $obj_name,
2506 - 'object_id' => $obj_id,
2507 - );
2508 - $this->wpdb->insert( $this->table_name( 'lookup_item_objects' ), $data );
2509 - return $this->wpdb->insert_id; // must return lookup id.
2510 - }
1978 + if ( self::use_mysqli() ) {
1979 + return mysqli_fetch_array( $result, ( $result_type == null ? MYSQLI_BOTH : $result_type ) );
1980 + } else {
1981 + return mysql_fetch_array( $result, ( $result_type == null ? MYSQL_BOTH : $result_type ) );
1982 + }
1983 + }
2511 1984
2512 - /**
2513 - * Method delete_lookup_items().
2514 - *
2515 - * Delete bulk lookup items by lookup ids or object names with item id and item name, to reduce number of db queries.
2516 - *
2517 - * @param string $by Delete by.
2518 - * @param array $params params.
2519 - *
2520 - * @return mixed Result
2521 - */
2522 - public function delete_lookup_items( $by = 'lookup_id', $params = array() ) { // phpcs:ignore -- NOSONAR - complex.
2523 - if ( ! is_array( $params ) ) {
2524 - return false;
2525 - }
1985 + public static function num_rows( $result ) {
1986 + if ( $result === false ) {
1987 + return 0;
1988 + }
2526 1989
2527 - $lookup_ids = isset( $params['lookup_ids'] ) ? $params['lookup_ids'] : null;
2528 - $item_id = isset( $params['item_id'] ) ? $params['item_id'] : null;
2529 - $object_id = isset( $params['object_id'] ) ? $params['object_id'] : null;
2530 - $item_name = isset( $params['item_name'] ) ? $params['item_name'] : null;
2531 - $obj_names = isset( $params['object_names'] ) ? $params['object_names'] : null;
1990 + if ( self::use_mysqli() ) {
1991 + return mysqli_num_rows( $result );
1992 + } else {
1993 + return mysql_num_rows( $result );
1994 + }
1995 + }
2532 1996
2533 - if ( 'object_name' === $by ) {
2534 - if ( empty( $item_id ) || empty( $item_name ) ) {
2535 - return false;
2536 - }
1997 + public static function is_result( $result ) {
1998 + if ( $result === false ) {
1999 + return false;
2000 + }
2537 2001
2538 - $obj_names = $this->escape_array( $obj_names );
2539 - if ( ! empty( $obj_names ) ) {
2540 - $this->wpdb->query( $this->wpdb->prepare( 'DELETE FROM ' . $this->table_name( 'lookup_item_objects' ) . ' WHERE item_name = %s AND item_id = %d AND object_name IN ("' . implode( '","', $obj_names ) . '") ', $item_name, $item_id ) ); //phpcs:ignore -- ok.
2541 - return true;
2542 - }
2543 - } elseif ( 'object_id' === $by ) {
2544 - if ( empty( $object_id ) || empty( $item_name ) || empty( $obj_names ) ) {
2545 - return false;
2546 - }
2002 + if ( self::use_mysqli() ) {
2003 + return ( $result instanceof mysqli_result );
2004 + } else {
2005 + return is_resource( $result );
2006 + }
2007 + }
2547 2008
2548 - $obj_names = $this->escape_array( $obj_names );
2549 - if ( ! empty( $obj_names ) ) {
2550 - $this->wpdb->query( $this->wpdb->prepare( 'DELETE FROM ' . $this->table_name( 'lookup_item_objects' ) . ' WHERE item_name = %s AND object_id = %d AND object_name IN ("' . implode( '","', $obj_names ) . '") ', $item_name, $object_id ) ); //phpcs:ignore -- ok.
2551 - return true;
2552 - }
2553 - } elseif ( 'lookup_id' === $by ) {
2554 - if ( empty( $lookup_ids ) ) {
2555 - return false;
2556 - }
2557 - if ( is_numeric( $lookup_ids ) ) {
2558 - $lookup_ids = array( $lookup_ids );
2559 - } elseif ( is_array( $lookup_ids ) ) {
2560 - $lookup_ids = MainWP_Utility::array_numeric_filter( $lookup_ids );
2561 - } else {
2562 - return false;
2563 - }
2564 - $this->wpdb->query( 'DELETE FROM ' . $this->table_name( 'lookup_item_objects' ) . ' WHERE lookup_id IN (' . implode( ',', $lookup_ids ) . ') ' ); //phpcs:ignore -- ok.
2565 - return true;
2566 - }
2567 - return false;
2568 - }
2569 2009 }
2010 +
2011 +?>