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-utility.php +3216 -1423 5.14.0.5 View file →
@@ -1,1622 +1,3415 @@
1 1 <?php
2 -/**
3 - * MainWP Utility Helper.
4 - *
5 - * @package MainWP/Dashboard
6 - */
7 2
8 -namespace MainWP\Dashboard;
3 +class MainWP_Utility {
9 4
10 -// phpcs:disable WordPress.DB.RestrictedFunctions, WordPress.WP.AlternativeFunctions, WordPress.PHP.NoSilencedErrors, Generic.Metrics.CyclomaticComplexity -- Using cURL functions.
5 + public static $enabled_wp_seo = null;
11 6
12 -/**
13 - * Class MainWP_Utility
14 - *
15 - * @package MainWP\Dashboard
16 - */
17 -class MainWP_Utility { // phpcs:ignore Generic.Classes.OpeningBraceSameLine.ContentAfterBrace -- NOSONAR.
7 + public static function startsWith( $haystack, $needle ) {
8 + return !strncmp( $haystack, $needle, strlen( $needle ) );
9 + }
18 10
19 - /**
20 - * Yoast SEO is enabled return true else return null.
21 - *
22 - * @static
23 - * @var boolean $enabled_wp_seo If Yoast SEO is enabled return true else return null.
24 - */
25 - public static $enabled_wp_seo = null;
11 + public static function endsWith( $haystack, $needle ) {
12 + $length = strlen( $needle );
13 + if ( $length == 0 ) {
14 + return true;
15 + }
26 16
27 - /**
28 - * Private static variable.
29 - *
30 - * @static
31 - *
32 - * @var mixed Default null
33 - */
34 - public static $last_deactivated_alerts = null;
17 + return ( substr( $haystack, - $length ) === $needle );
18 + }
35 19
36 - /**
37 - * Private static variable to hold the single instance of the class.
38 - *
39 - * @static
40 - *
41 - * @var mixed Default null
42 - */
43 - private static $instance = null;
20 + public static function getNiceURL( $pUrl, $showHttp = false ) {
21 + $url = $pUrl;
44 22
45 - /**
46 - * Store the disabled php functions.
47 - *
48 - * @static
49 - * @var string $disabled_functions disabled php functions.
50 - */
51 - public static $disabled_functions = null;
23 + if ( self::startsWith( $url, 'http://' ) ) {
24 + if ( !$showHttp ) {
25 + $url = substr( $url, 7 );
26 + }
27 + } else if ( self::startsWith( $pUrl, 'https://' ) ) {
28 + if ( !$showHttp ) {
29 + $url = substr( $url, 8 );
30 + }
31 + } else {
32 + if ( $showHttp ) {
33 + $url = 'http://' . $url;
34 + }
35 + }
52 36
53 - /**
54 - * Method get_class_name()
55 - *
56 - * Get Class Name.
57 - *
58 - * @return object __CLASS__
59 - */
60 - public static function get_class_name() {
61 - return __CLASS__;
62 - }
37 + if ( self::endsWith( $url, '/' ) ) {
38 + if ( !$showHttp ) {
39 + $url = substr( $url, 0, strlen( $url ) - 1 );
40 + }
41 + } else {
42 + $url = $url . '/';
43 + }
63 44
64 - /**
65 - * Method instance()
66 - *
67 - * Create public static instance.
68 - *
69 - * @static
70 - * @return MainWP_Utility
71 - */
72 - public static function instance() {
73 - if ( null === static::$instance ) {
74 - static::$instance = new self();
75 - }
45 + return $url;
46 + }
76 47
77 - return static::$instance;
78 - }
48 + public static function limitString( $pInput, $pMax = 500 ) {
49 + $output = strip_tags( $pInput );
50 + if ( strlen( $output ) > $pMax ) {
51 + // truncate string
52 + $outputCut = substr( $output, 0, $pMax );
53 + // make sure it ends in a word so assassinate doesn't become ass...
54 + $output = substr( $outputCut, 0, strrpos( $outputCut, ' ' ) ) . '...';
55 + }
56 + echo $output;
57 + }
79 58
80 - /**
81 - * Method starts_with()
82 - *
83 - * Start of Stack Trace.
84 - *
85 - * @param mixed $haystack The full stack.
86 - * @param mixed $needle The function that is throwing the error.
87 - *
88 - * @return mixed Needle in the Haystack.
89 - */
90 - public static function starts_with( $haystack, $needle ) {
91 - return ! strncmp( $haystack, $needle, strlen( $needle ) );
92 - }
59 + public static function isAdmin() {
60 + global $current_user;
61 + if ( $current_user->ID == 0 ) {
62 + return false;
63 + }
93 64
94 - /**
95 - * Method ends_with()
96 - *
97 - * End of Stack Trace.
98 - *
99 - * @param mixed $haystack Haystack parameter.
100 - * @param mixed $needle Needle parameter.
101 - *
102 - * @return boolean
103 - */
104 - public static function ends_with( $haystack, $needle ) {
105 - $length = strlen( $needle );
106 - if ( 0 === $length ) {
107 - return true;
108 - }
65 + if ( $current_user->wp_user_level == 10 || ( isset( $current_user->user_level ) && $current_user->user_level == 10 ) || current_user_can( 'level_10' ) ) {
66 + return true;
67 + }
109 68
110 - return substr( $haystack, - $length ) === $needle;
111 - }
69 + return false;
70 + }
112 71
113 - /**
114 - * Method get_nice_url()
115 - *
116 - * Grab url.
117 - *
118 - * @param string $pUrl Website URL.
119 - * @param bool $showHttp Show HTTP.
120 - *
121 - * @return string $url.
122 - */
123 - public static function get_nice_url( $pUrl, $showHttp = false ) {
124 - $url = $pUrl;
72 + public static function isWebsiteAvailable( $website ) {
73 + $http_user = null;
74 + $http_pass = null;
75 + $sslVersion = null;
76 + $verifyCertificate = null;
77 + $forceUseIPv4 = null;
78 + if ( is_object( $website ) && isset( $website->url ) ) {
79 + $url = $website->url;
80 + $verifyCertificate = isset( $website->verify_certificate ) ? $website->verify_certificate : null;
81 + $forceUseIPv4 = $website->force_use_ipv4;
82 + $http_user = $website->http_user;
83 + $http_pass = $website->http_pass;
84 + $sslVersion = $website->ssl_version;
85 + } else {
86 + $url = $website;
87 + }
125 88
126 - if ( static::starts_with( $url, 'http://' ) ) {
127 - if ( ! $showHttp ) {
128 - $url = substr( $url, 7 );
129 - }
130 - } elseif ( static::starts_with( $pUrl, 'https://' ) ) {
131 - if ( ! $showHttp ) {
132 - $url = substr( $url, 8 );
133 - }
134 - } elseif ( $showHttp ) {
135 - $url = 'http://' . $url;
136 - }
89 + if ( !self::isDomainValid( $url ) ) {
90 + return false;
91 + }
137 92
138 - if ( static::ends_with( $url, '/' ) ) {
139 - if ( ! $showHttp ) {
140 - $url = substr( $url, 0, strlen( $url ) - 1 );
141 - }
142 - } else {
143 - $url = $url . '/';
144 - }
93 + return MainWP_Utility::tryVisit( $url, $verifyCertificate, $http_user, $http_pass, $sslVersion, $forceUseIPv4 );
94 + }
145 95
146 - return $url;
147 - }
96 + private static function isDomainValid( $url ) {
97 + //check, if a valid url is provided
98 + return filter_var( $url, FILTER_VALIDATE_URL );
99 + }
148 100
149 - /**
150 - * Method is_domain_valid()
151 - *
152 - * Check $url against FILTER_VALIDATE_URL.
153 - *
154 - * @param mixed $url Domain to check.
155 - *
156 - * @return boolean True|False.
157 - */
158 - public static function is_domain_valid( $url ) {
159 - return filter_var( $url, FILTER_VALIDATE_URL );
160 - }
101 + public static function tryVisit( $url, $verifyCertificate = null, $http_user = null, $http_pass = null, $sslVersion = 0, $forceUseIPv4 = null ) {
161 102
162 - /**
163 - * Method ctype_digit()
164 - *
165 - * Returns TRUE if every character in the string text is a decimal digit, FALSE otherwise.
166 - *
167 - * @param mixed $str String to check.
168 - *
169 - * @return boolean Returns TRUE if every character in the string text is a decimal digit, FALSE otherwise.
170 - */
171 - public static function ctype_digit( $str ) {
172 - return ( is_string( $str ) || is_int( $str ) || is_float( $str ) ) && preg_match( '/^\d+\z/', $str );
173 - }
103 + $agent = 'Mozilla/5.0 (compatible; MainWP/' . MainWP_System::$version . '; +http://mainwp.com)';
104 + $postdata = array( 'test' => 'yes' );
174 105
175 - /**
176 - * Method sortmulti()
177 - *
178 - * Sort the given array, Acending, Decending or by Natural Order.
179 - *
180 - * @param mixed $arr Array to sort.
181 - * @param mixed $index Index of array.
182 - * @param mixed $order Acending or Decending order.
183 - * @param bool $natsort Sort an array using a "natural order" algorithm. Default: false.
184 - * @param bool $case_sensitive If case sensitive return true else return false. Default: false.
185 - *
186 - * @return array $sorted Return the sorted array.
187 - */
188 - public static function sortmulti( $arr, $index, $order, $natsort = false, $case_sensitive = false ) { // phpcs:ignore -- NOSONAR - complex.
189 - $sorted = array();
190 - if ( is_array( $arr ) && ! empty( $arr ) ) {
191 - foreach ( array_keys( $arr ) as $key ) {
192 - $temp[ $key ] = $arr[ $key ][ $index ];
193 - }
194 - if ( ! $natsort ) {
195 - if ( 'asc' === $order ) {
196 - asort( $temp );
197 - } else {
198 - arsort( $temp );
199 - }
200 - } else {
201 - if ( true === $case_sensitive ) {
202 - natsort( $temp );
203 - } else {
204 - natcasesort( $temp );
205 - }
206 - if ( 'asc' !== $order ) {
207 - $temp = array_reverse( $temp, true );
208 - }
209 - }
210 - foreach ( array_keys( $temp ) as $key ) {
211 - if ( is_numeric( $key ) ) {
212 - $sorted[] = $arr[ $key ];
213 - } else {
214 - $sorted[ $key ] = $arr[ $key ];
215 - }
216 - }
106 + $ch = curl_init();
217 107
218 - return $sorted;
219 - }
108 + // cURL offers really easy proxy support.
109 + $proxy = new WP_HTTP_Proxy();
110 + if ( $proxy->is_enabled() && $proxy->send_through_proxy( $url ) ) {
111 + curl_setopt( $ch, CURLOPT_PROXYTYPE, CURLPROXY_HTTP );
112 + curl_setopt( $ch, CURLOPT_PROXY, $proxy->host() );
113 + curl_setopt( $ch, CURLOPT_PROXYPORT, $proxy->port() );
220 114
221 - return $sorted;
222 - }
115 + if ( $proxy->use_authentication() ) {
116 + curl_setopt( $ch, CURLOPT_PROXYAUTH, CURLAUTH_ANY );
117 + curl_setopt( $ch, CURLOPT_PROXYUSERPWD, $proxy->authentication() );
118 + }
119 + }
223 120
224 - /**
225 - * Method get_sub_array_having()
226 - *
227 - * Get sub array.
228 - *
229 - * @param mixed $arr Array to traverse.
230 - * @param mixed $index Index of array.
231 - * @param mixed $value Array values.
232 - *
233 - * void array $output Sub array.
234 - */
235 - public static function get_sub_array_having( $arr, $index, $value ) {
236 - $output = array();
237 - if ( is_array( $arr ) && ! empty( $arr ) ) {
238 - foreach ( $arr as $arrvalue ) {
239 - $existed = isset( $arrvalue[ $index ] ) ? $arrvalue[ $index ] : null;
240 - if ( $existed === $value ) {
241 - $output[] = $arrvalue;
242 - }
243 - }
244 - }
121 + curl_setopt( $ch, CURLOPT_URL, $url );
122 + curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
123 + curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, true );
124 + curl_setopt( $ch, CURLOPT_POST, true );
125 + curl_setopt( $ch, CURLOPT_POSTFIELDS, $postdata );
126 + curl_setopt( $ch, CURLOPT_CONNECTTIMEOUT, 10 );
127 + curl_setopt( $ch, CURLOPT_USERAGENT, $agent );
128 + curl_setopt( $ch, CURLOPT_ENCODING, 'none'); // to fix
245 129
246 - return $output;
247 - }
130 + if ( !empty( $http_user ) && !empty( $http_pass ) ) {
131 + $http_pass = stripslashes($http_pass); // to fix
132 + curl_setopt( $ch, CURLOPT_USERPWD, "$http_user:$http_pass" );
133 + }
248 134
249 - /**
250 - * Method trim_slashes()
251 - *
252 - * Trim stashes from element.
253 - *
254 - * @param mixed $elem Element to trim.
255 - *
256 - * @return string Return string with no slashes.
257 - */
258 - public static function trim_slashes( $elem ) {
259 - return trim( $elem, '/' );
260 - }
135 + $ssl_verifyhost = false;
136 + if ( $verifyCertificate !== null ) {
137 + if ( $verifyCertificate == 1 ) {
138 + $ssl_verifyhost = true;
139 + } else if ( $verifyCertificate == 2 ) { // use global setting
140 + if ( ( ( get_option( 'mainwp_sslVerifyCertificate' ) === false ) || ( get_option( 'mainwp_sslVerifyCertificate' ) == 1 ) ) ) {
141 + $ssl_verifyhost = true;
142 + }
143 + }
144 + } else {
145 + if ( ( ( get_option( 'mainwp_sslVerifyCertificate' ) === false ) || ( get_option( 'mainwp_sslVerifyCertificate' ) == 1 ) ) ) {
146 + $ssl_verifyhost = true;
147 + }
148 + }
261 149
262 - /**
263 - * Method sanitize()
264 - *
265 - * Sanitize given string.
266 - *
267 - * @param mixed $str String to sanitize.
268 - *
269 - * @return string Sanitized string.
270 - */
271 - public static function sanitize( $str ) {
272 - return preg_replace( '/[\\\\\/\:"\*\?\<\>\|]+/', '', $str );
273 - }
150 + if ( $ssl_verifyhost ) {
151 + @curl_setopt( $ch, CURLOPT_SSL_VERIFYHOST, 2 );
152 + @curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, true );
153 + } else {
154 + @curl_setopt( $ch, CURLOPT_SSL_VERIFYHOST, false );
155 + @curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, false );
156 + }
274 157
275 - /**
276 - * Method sanitize_alphanumeric()
277 - *
278 - * Sanitize given string.
279 - *
280 - * @param mixed $str String to sanitize.
281 - *
282 - * @return string Sanitized string.
283 - */
284 - public static function sanitize_attr_slug( $str ) {
285 - $str = strtolower( $str );
286 - $str = str_replace( array( '=', '?', '/' ), '-', $str );
287 - $str = preg_replace( '/[^A-Za-z0-9^\-]/', '', $str );
288 - return $str;
289 - }
158 + @curl_setopt( $ch, CURLOPT_SSLVERSION, $sslVersion );
159 + @curl_setopt( $ch, CURLOPT_HTTPHEADER, array( "X-Requested-With: XMLHttpRequest" ) );
160 + @curl_setopt( $ch, CURLOPT_REFERER, get_option( 'siteurl' ) );
290 161
291 - /**
292 - * Method end_session()
293 - *
294 - * End a session.
295 - *
296 - * @return void
297 - */
298 - public static function end_session() {
162 + $force_use_ipv4 = false;
163 + if ( $forceUseIPv4 !== null ) {
164 + if ( $forceUseIPv4 == 1 ) {
165 + $force_use_ipv4 = true;
166 + } else if ( $forceUseIPv4 == 2 ) { // use global setting
167 + if ( get_option( 'mainwp_forceUseIPv4' ) == 1 ) {
168 + $force_use_ipv4 = true;
169 + }
170 + }
171 + } else {
172 + if ( get_option( 'mainwp_forceUseIPv4' ) == 1 ) {
173 + $force_use_ipv4 = true;
174 + }
175 + }
299 176
300 - if ( defined( 'WP_CLI' ) && WP_CLI ) {
301 - return;
302 - }
177 + if ( $force_use_ipv4 ) {
178 + if ( defined( 'CURLOPT_IPRESOLVE' ) AND defined( 'CURL_IPRESOLVE_V4' ) ) {
179 + @curl_setopt( $ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4 );
180 + }
181 + }
303 182
304 - if ( defined( 'DOING_CRON' ) && DOING_CRON ) {
305 - return;
306 - }
183 + $disabled_functions = ini_get( 'disable_functions' );
184 + if ( empty( $disabled_functions ) || ( stristr( $disabled_functions, 'curl_multi_exec' ) === false ) ) {
185 + $mh = curl_multi_init();
186 + @curl_multi_add_handle( $mh, $ch );
307 187
308 - session_write_close();
309 - if ( 0 < ob_get_length() ) {
310 - ob_end_flush();
311 - }
312 - }
188 + do {
189 + curl_multi_exec( $mh, $running ); //Execute handlers
190 + while ( $info = curl_multi_info_read( $mh ) ) {
191 + $data = curl_multi_getcontent( $info[ 'handle' ] );
192 + $err = curl_error( $info[ 'handle' ] );
193 + $http_status = curl_getinfo( $info[ 'handle' ], CURLINFO_HTTP_CODE );
194 + $errno = curl_errno( $info[ 'handle' ] );
195 + $realurl = curl_getinfo( $info[ 'handle' ], CURLINFO_EFFECTIVE_URL );
313 196
314 - /**
315 - * Method get_timestamp()
316 - *
317 - * Get time stamp in gmt_offset.
318 - *
319 - * @param mixed $timestamp Time stamp to convert.
320 - *
321 - * @return string Time stamp in general mountain time offset.
322 - */
323 - public static function get_timestamp( $timestamp = false ) {
324 - if ( false === $timestamp ) {
325 - $timestamp = time();
326 - }
327 - $gmtOffset = get_option( 'gmt_offset' );
197 + curl_multi_remove_handle( $mh, $info[ 'handle' ] );
198 + }
199 + usleep( 10000 );
200 + } while ( $running > 0 );
328 201
329 - return $gmtOffset ? ( $gmtOffset * HOUR_IN_SECONDS ) + $timestamp : $timestamp;
330 - }
202 + curl_multi_close( $mh );
203 + } else {
204 + $data = curl_exec( $ch );
205 + $err = curl_error( $ch );
206 + $http_status = curl_getinfo( $ch, CURLINFO_HTTP_CODE );
207 + $errno = curl_errno( $ch );
208 + $realurl = curl_getinfo( $ch, CURLINFO_EFFECTIVE_URL );
209 + curl_close( $ch );
210 + }
331 211
332 - /**
333 - * Method date()
334 - *
335 - * Show date in given format.
336 - *
337 - * @param mixed $format Format to display date in.
338 - *
339 - * @return string Date.
340 - */
341 - public static function date( $format ) {
342 - // phpcs:ignore -- use local date function.
343 - return date( $format, static::get_timestamp() );
344 - }
212 + MainWP_Logger::Instance()->debug( ' :: tryVisit :: [url=' . $url . '] [http_status=' . $http_status . '] [error=' . $err . '] [data=' . $data . ']' );
345 213
346 - /**
347 - * Method format_timestamp()
348 - *
349 - * Format the given timestamp.
350 - *
351 - * @param mixed $timestamp Timestamp to format.
352 - *
353 - * @return string Formatted timestamp.
354 - */
355 - public static function format_timestamp( $timestamp ) {
356 - return date_i18n( get_option( 'date_format' ) . ' ' . get_option( 'time_format' ), $timestamp );
357 - }
214 + $host = parse_url( ( empty( $realurl ) ? $url : $realurl ), PHP_URL_HOST );
215 + $ip = false;
216 + $target = false;
358 217
359 - /**
360 - * Method format_timestamp()
361 - *
362 - * Format the given timestamp.
363 - *
364 - * @param mixed $timestamp Timestamp to format.
365 - *
366 - * @return string Formatted timestamp.
367 - */
368 - public static function format_date( $timestamp ) {
369 - return date_i18n( get_option( 'date_format' ), $timestamp );
370 - }
218 + $dnsRecord = @dns_get_record( $host );
219 + MainWP_Logger::Instance()->debug( ' :: tryVisit :: [dnsRecord=' . print_r( $dnsRecord, 1 ) . ']' );
220 + if ( $dnsRecord === false ) {
221 + $data = false;
222 + } else if ( is_array( $dnsRecord ) ) {
223 + if ( !isset( $dnsRecord[ 'ip' ] ) ) {
224 + foreach ( $dnsRecord as $dnsRec ) {
225 + if ( isset( $dnsRec[ 'ip' ] ) ) {
226 + $ip = $dnsRec[ 'ip' ];
227 + break;
228 + }
229 + }
230 + } else {
231 + $ip = $dnsRecord[ 'ip' ];
232 + }
371 233
372 - /**
373 - * Format duration time to show.
374 - *
375 - * @param float $time timestamp.
376 - * @return mixed result.
377 - */
378 - public static function format_duration_time( $time ) {
234 + $found = false;
235 + if ( !isset( $dnsRecord[ 'host' ] ) ) {
236 + foreach ( $dnsRecord as $dnsRec ) {
237 + if ( $dnsRec[ 'host' ] == $host ) {
238 + if ( $dnsRec[ 'type' ] == 'CNAME' ) {
239 + $target = $dnsRec[ 'target' ];
240 + }
241 + $found = true;
242 + break;
243 + }
244 + }
245 + } else {
246 + $found = ( $dnsRecord[ 'host' ] == $host );
247 + if ( $dnsRecord[ 'type' ] == 'CNAME' ) {
248 + $target = $dnsRecord[ 'target' ];
249 + }
250 + }
379 251
380 - $original_sec = absint( $time );
381 - $dura_sec = $original_sec;
382 - $days = floor( $dura_sec / 86400 );
383 - $dura_sec -= $days * 86400;
384 - $dura_hour_sec = $dura_sec;
385 - $dura_hours = floor( $dura_sec / 3600 );
252 + if ( !$found ) {
253 + $data = false;
254 + //return array( 'error' => ( $err == '' ? 'Invalid host.' : $err ) ); // Got redirected to: ' . $dnsRecord['host'])));
255 + }
256 + }
386 257
387 - if ( $days > 0 ) {
388 - $formatted_dura = ( $days * 24 + $dura_hours ) . gmdate( 'i\m s\s', $dura_hour_sec );
389 - } else {
390 - $formatted_dura = gmdate( 'H\h i\m s\s', $original_sec );
391 - }
392 - return '<bdi>' . esc_html( $formatted_dura ) . '</bdi>';
393 - }
258 + if ( $ip === false ) {
259 + $ip = gethostbynamel( $host );
260 + }
261 + if ( ( $target !== false ) && ( $target != $host ) ) {
262 + $host .= ' (CNAME: ' . $target . ')';
263 + }
394 264
265 + $out = array(
266 + 'host' => $host,
267 + 'httpCode' => $http_status,
268 + 'error' => ( $err == '' && $data === false ? 'Invalid host.' : $err ),
269 + 'httpCodeString' => self::getHttpStatusErrorString( $http_status ),
270 + );
271 + if ( $ip !== false ) {
272 + $out[ 'ip' ] = $ip;
273 + }
395 274
396 - /**
397 - * Method human_filesize()
398 - *
399 - * Convert to human readable file size format,
400 - * (B|kB|MB|GB|TB|PB|EB|ZB|YB).
401 - *
402 - * @param mixed $bytes File in bytes.
403 - * @param integer $decimals Number of decimals to output.
404 - *
405 - * @return string Human readable file size.
406 - */
407 - public static function human_filesize( $bytes, $decimals = 2 ) {
408 - $size = array( 'B', 'kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB' );
409 - $factor = floor( ( strlen( $bytes ) - 1 ) / 3 );
275 + return $out;
276 + }
410 277
411 - return sprintf( "%.{$decimals}f", $bytes / pow( 1024, $factor ) ) . @$size[ $factor ];
412 - }
278 + protected static function getHttpStatusErrorString( $httpCode ) {
279 + if ( $httpCode == 100 ) {
280 + return 'Continue';
281 + }
282 + if ( $httpCode == 101 ) {
283 + return 'Switching Protocols';
284 + }
285 + if ( $httpCode == 200 ) {
286 + return 'OK';
287 + }
288 + if ( $httpCode == 201 ) {
289 + return 'Created';
290 + }
291 + if ( $httpCode == 202 ) {
292 + return 'Accepted';
293 + }
294 + if ( $httpCode == 203 ) {
295 + return 'Non-Authoritative Information';
296 + }
297 + if ( $httpCode == 204 ) {
298 + return 'No Content';
299 + }
300 + if ( $httpCode == 205 ) {
301 + return 'Reset Content';
302 + }
303 + if ( $httpCode == 206 ) {
304 + return 'Partial Content';
305 + }
306 + if ( $httpCode == 300 ) {
307 + return 'Multiple Choices';
308 + }
309 + if ( $httpCode == 301 ) {
310 + return 'Moved Permanently';
311 + }
312 + if ( $httpCode == 302 ) {
313 + return 'Found';
314 + }
315 + if ( $httpCode == 303 ) {
316 + return 'See Other';
317 + }
318 + if ( $httpCode == 304 ) {
319 + return 'Not Modified';
320 + }
321 + if ( $httpCode == 305 ) {
322 + return 'Use Proxy';
323 + }
324 + if ( $httpCode == 306 ) {
325 + return '(Unused)';
326 + }
327 + if ( $httpCode == 307 ) {
328 + return 'Temporary Redirect';
329 + }
330 + if ( $httpCode == 400 ) {
331 + return 'Bad Request';
332 + }
333 + if ( $httpCode == 401 ) {
334 + return 'Unauthorized';
335 + }
336 + if ( $httpCode == 402 ) {
337 + return 'Payment Required';
338 + }
339 + if ( $httpCode == 403 ) {
340 + return 'Forbidden';
341 + }
342 + if ( $httpCode == 404 ) {
343 + return 'Not Found';
344 + }
345 + if ( $httpCode == 405 ) {
346 + return 'Method Not Allowed';
347 + }
348 + if ( $httpCode == 406 ) {
349 + return 'Not Acceptable';
350 + }
351 + if ( $httpCode == 407 ) {
352 + return 'Proxy Authentication Required';
353 + }
354 + if ( $httpCode == 408 ) {
355 + return 'Request Timeout';
356 + }
357 + if ( $httpCode == 409 ) {
358 + return 'Conflict';
359 + }
360 + if ( $httpCode == 410 ) {
361 + return 'Gone';
362 + }
363 + if ( $httpCode == 411 ) {
364 + return 'Length Required';
365 + }
366 + if ( $httpCode == 412 ) {
367 + return 'Precondition Failed';
368 + }
369 + if ( $httpCode == 413 ) {
370 + return 'Request Entity Too Large';
371 + }
372 + if ( $httpCode == 414 ) {
373 + return 'Request-URI Too Long';
374 + }
375 + if ( $httpCode == 415 ) {
376 + return 'Unsupported Media Type';
377 + }
378 + if ( $httpCode == 416 ) {
379 + return 'Requested Range Not Satisfiable';
380 + }
381 + if ( $httpCode == 417 ) {
382 + return 'Expectation Failed';
383 + }
384 + if ( $httpCode == 500 ) {
385 + return 'Internal Server Error';
386 + }
387 + if ( $httpCode == 501 ) {
388 + return 'Not Implemented';
389 + }
390 + if ( $httpCode == 502 ) {
391 + return 'Bad Gateway';
392 + }
393 + if ( $httpCode == 503 ) {
394 + return 'Service Unavailable';
395 + }
396 + if ( $httpCode == 504 ) {
397 + return 'Gateway Timeout';
398 + }
399 + if ( $httpCode == 505 ) {
400 + return 'HTTP Version Not Supported';
401 + }
413 402
414 - /**
415 - * Method map_fields()
416 - *
417 - * Map Site.
418 - *
419 - * @param mixed $data data to map.
420 - * @param mixed $keys Keys to map.
421 - * @param bool $object_output Output format array|object.
422 - *
423 - * @return mixed Mapped data.
424 - */
425 - public static function map_fields( &$data, $keys, $object_output = true ) {
426 - return static::map_site( $data, $keys, $object_output );
427 - }
403 + return null;
404 + }
428 405
429 - /**
430 - * Method map_site()
431 - *
432 - * Map Site.
433 - *
434 - * @param mixed $website Website to map.
435 - * @param mixed $keys Keys to map.
436 - * @param bool $object_output Output format array|object.
437 - *
438 - * @return mixed $outputSite Mapped site.
439 - */
440 - public static function map_site( &$website, $keys, $object_output = true ) { // phpcs:ignore -- NOSONAR - complex.
441 - if ( $object_output ) {
442 - $outputSite = new \stdClass();
443 - if ( ! empty( $website ) ) {
444 - if ( is_object( $website ) ) {
445 - foreach ( $keys as $key ) {
446 - $outputSite->{$key} = $website->$key;
406 + static function check_ignored_http_code( $value ) {
407 + if ( $value == 200 )
408 + return true;
409 +
410 + $ignored_code = get_option( 'mainwp_ignore_HTTP_response_status', '' );
411 + $ignored_code = trim( $ignored_code );
412 + if ( !empty( $ignored_code ) ) {
413 + $ignored_code = explode( ',', $ignored_code );
414 + foreach ( $ignored_code as $code ) {
415 + $code = trim( $code );
416 + if ( $value == $code ) {
417 + return true;
418 + }
419 + }
420 + }
421 + return false;
422 + }
423 +
424 + public static function utf8ize($mixed) {
425 + if (is_array($mixed)) {
426 + foreach ($mixed as $key => $value) {
427 + $mixed[$key] = self::utf8ize($value);
428 + }
429 + } elseif (is_string($mixed)) {
430 + if ( function_exists( 'mb_convert_encoding' )) {
431 + return mb_convert_encoding($mixed, "UTF-8", "UTF-8");
432 + }
433 + }
434 + return $mixed;
435 + }
436 +
437 + public static function safe_json_encode($value, $options = 0, $depth = 512) {
438 + $encoded = @json_encode($value, $options, $depth);
439 + if ($encoded === false && $value && json_last_error() == JSON_ERROR_UTF8) {
440 + $encoded = @json_encode(self::utf8ize($value), $options, $depth);
441 + }
442 + return $encoded;
443 + }
444 +
445 + static function activated_primary_backup_plugin( $what, $website ) {
446 + $plugins = json_decode( $website->plugins, 1 );
447 + if ( !is_array( $plugins ) || count( $plugins ) == 0 ) {
448 + return false;
449 + }
450 +
451 + $installed = false;
452 + switch ( $what ) {
453 + case 'backupbuddy':
454 + foreach ( $plugins as $plugin ) {
455 + if ( ('backupbuddy/backupbuddy.php' == strtolower( $plugin[ 'slug' ] ) ) ) {
456 + if ( $plugin[ 'active' ] ) {
457 + $installed = true;
458 + }
459 + break;
460 + }
461 + }
462 + break;
463 + case 'backupwp':
464 + foreach ( $plugins as $plugin ) {
465 + if ( ('backupwordpress/backupwordpress.php' == $plugin[ 'slug' ] ) ) {
466 + if ( $plugin[ 'active' ] ) {
467 + $installed = true;
468 + }
469 + break;
470 + }
471 + }
472 + break;
473 + case 'backwpup':
474 + foreach ( $plugins as $plugin ) {
475 + if ( ( strcmp( $plugin[ 'slug' ], "backwpup/backwpup.php" ) === 0 ) || strcmp( $plugin[ 'slug' ], "backwpup-pro/backwpup.php" ) === 0 ) {
476 + if ( $plugin[ 'active' ] ) {
477 + $installed = true;
478 + }
479 + break;
480 + }
481 + }
482 + break;
483 + case 'updraftplus':
484 + foreach ( $plugins as $plugin ) {
485 + if ( ('updraftplus/updraftplus.php' == $plugin[ 'slug' ] ) ) {
486 + if ( $plugin[ 'active' ] ) {
487 + $installed = true;
488 + }
489 + break;
490 + }
491 + }
492 + break;
493 + }
494 + return $installed;
495 + }
496 +
497 + public static function get_primary_backup() {
498 + $enable_legacy_backup = get_option( 'mainwp_enableLegacyBackupFeature' );
499 + if ( !$enable_legacy_backup ) {
500 + return get_option( 'mainwp_primaryBackup', false );
501 + }
502 + return false;
503 + }
504 +
505 + static function getNotificationEmail( $user = null ) {
506 + if ( $user == null ) {
507 + global $current_user;
508 + $user = $current_user;
509 + }
510 +
511 + if ( $user == null ) {
512 + return null;
513 + }
514 +
515 + if ( !( $user instanceof WP_User ) ) {
516 + return null;
517 + }
518 +
519 + $userExt = MainWP_DB::Instance()->getUserExtension();
520 + if ( $userExt->user_email != '' ) {
521 + return $userExt->user_email;
522 + }
523 +
524 + return $user->user_email;
525 + }
526 +
527 + /*
528 + * $website: Expected object ($website->id, $website->url, ... returned by MainWP_DB)
529 + * $what: What function needs to be called - defined in the mainwpplugin
530 + * $params: (Optional) array(key => value, key => value);
531 + */
532 +
533 + static function getPostDataAuthed( &$website, $what, $params = null ) {
534 + if ( $website && $what != '' ) {
535 + $data = array();
536 + $data[ 'user' ] = $website->adminname;
537 + $data[ 'function' ] = $what;
538 + $data[ 'nonce' ] = rand( 0, 9999 );
539 + if ( $params != null ) {
540 + $data = array_merge( $data, $params );
541 + }
542 +
543 + if ( ( $website->nossl == 0 ) && function_exists( 'openssl_verify' ) ) {
544 + $data[ 'nossl' ] = 0;
545 + @openssl_sign( $what . $data[ 'nonce' ], $signature, base64_decode( $website->privkey ) );
546 + } else {
547 + $data[ 'nossl' ] = 1;
548 + $signature = md5( $what . $data[ 'nonce' ] . $website->nosslkey );
549 + }
550 + $data[ 'mainwpsignature' ] = base64_encode( $signature );
551 +
552 + $recent_number = apply_filters('mainwp_recent_posts_pages_number', 5);
553 + if ( $recent_number != 5 ) {
554 + $data[ 'recent_number' ] = $recent_number;
555 + }
556 +
557 + global $current_user;
558 +
559 + if ( (! defined( 'DOING_CRON' ) || false === DOING_CRON) && ( !defined('WP_CLI') || false === WP_CLI ) ) {
560 + if ( is_object( $current_user ) && property_exists( $current_user, 'ID' ) && $current_user->ID ) {
561 + $alter_user = apply_filters('mainwp_alter_login_user', false, $website->id);
562 + if (!empty( $alter_user )) {
563 + $data['alt_user'] = rawurlencode($alter_user);
447 564 }
448 - } elseif ( is_array( $website ) ) {
449 - foreach ( $keys as $key ) {
450 - $outputSite->{$key} = $website[ $key ];
451 - }
452 565 }
453 566 }
454 - } else {
455 - $outputSite = array();
456 - if ( ! empty( $website ) ) {
457 - if ( is_object( $website ) ) {
458 - foreach ( $keys as $key ) {
459 - $outputSite[ $key ] = $website->$key;
567 +
568 + return http_build_query( $data, '', '&' );
569 + }
570 +
571 + return null;
572 + }
573 +
574 + static function getGetDataAuthed( $website, $paramValue, $paramName = 'where', $asArray = false ) {
575 + $params = array();
576 + if ( $website && $paramValue != '' ) {
577 + $nonce = rand( 0, 9999 );
578 + if ( ( $website->nossl == 0 ) && function_exists( 'openssl_verify' ) ) {
579 + $nossl = 0;
580 + openssl_sign( $paramValue . $nonce, $signature, base64_decode( $website->privkey ) );
581 + } else {
582 + $nossl = 1;
583 + $signature = md5( $paramValue . $nonce . $website->nosslkey );
584 + }
585 + $signature = base64_encode( $signature );
586 +
587 + $params = array(
588 + 'login_required' => 1,
589 + 'user' => rawurlencode( $website->adminname ),
590 + 'mainwpsignature' => rawurlencode( $signature ),
591 + 'nonce' => $nonce,
592 + 'nossl' => $nossl,
593 + $paramName => rawurlencode( $paramValue ),
594 + );
595 +
596 + global $current_user;
597 + if ( (! defined( 'DOING_CRON' ) || false === DOING_CRON) && ( !defined('WP_CLI') || false === WP_CLI ) ) {
598 + if ( $current_user && $current_user->ID ) {
599 + $alter_user = apply_filters('mainwp_alter_login_user', false, $current_user->ID, $website->id);
600 + if (!empty( $alter_user )) {
601 + $params['alt_user'] = rawurlencode($alter_user);
460 602 }
461 - } elseif ( is_array( $website ) ) {
462 - foreach ( $keys as $key ) {
463 - $outputSite[ $key ] = $website[ $key ];
464 - }
465 603 }
466 604 }
467 - }
468 - return $outputSite;
469 - }
605 + }
470 606
471 - /**
472 - * Method array_merge()
473 - *
474 - * Merge two given arrays into one.
475 - *
476 - * @param mixed $arr1 First array.
477 - * @param mixed $arr2 Second array.
478 - *
479 - * @return array Merged Array.
480 - */
481 - public static function array_merge( $arr1, $arr2 ) {
482 - if ( ! is_array( $arr1 ) && ! is_array( $arr2 ) ) {
483 - return array();
484 - }
485 - if ( ! is_array( $arr1 ) ) {
486 - return $arr2;
487 - }
488 - if ( ! is_array( $arr2 ) ) {
489 - return $arr1;
490 - }
607 + if ( $asArray ) {
608 + return $params;
609 + }
491 610
492 - $output = array();
493 - foreach ( $arr1 as $el ) {
494 - $output[] = $el;
495 - }
496 - foreach ( $arr2 as $el ) {
497 - $output[] = $el;
498 - }
611 + $url = ( isset( $website->url ) && $website->url != '' ? $website->url : $website->siteurl );
612 + $url .= ( substr( $url, - 1 ) != '/' ? '/' : '' );
613 + $url .= '?';
499 614
500 - return $output;
501 - }
615 + foreach ( $params as $key => $value ) {
616 + $url .= $key . '=' . $value . '&';
617 + }
502 618
503 - /**
504 - * Method update_option()
505 - *
506 - * Update option.
507 - *
508 - * @param mixed $option_name Option name.
509 - * @param mixed $option_value Option value.
510 - *
511 - * @return (boolean) False if value was not updated and true if value was updated.
512 - */
513 - public static function update_option( $option_name, $option_value ) {
514 - $success = add_option( $option_name, $option_value, '', 'no' );
619 + return rtrim( $url, '&' );
620 + }
515 621
516 - if ( ! $success ) {
517 - $success = update_option( $option_name, $option_value );
518 - }
622 + /*
623 + * $url: String
624 + * $admin: admin username
625 + * $what: What function needs to be called - defined in the mainwpplugin
626 + * $params: (Optional) array(key => value, key => value);
627 + */
519 628
520 - return $success;
521 - }
629 + static function getPostDataNotAuthed( $url, $admin, $what, $params = null ) {
630 + if ( $url != '' && $admin != '' && $what != '' ) {
631 + $data = array();
632 + $data[ 'user' ] = $admin;
633 + $data[ 'function' ] = $what;
634 + if ( $params != null ) {
635 + $data = array_merge( $data, $params );
636 + }
522 637
523 - /**
524 - * Method update_user_option()
525 - *
526 - * Update option.
527 - *
528 - * @param mixed $option_name Option name.
529 - * @param mixed $option_value Option value.
530 - *
531 - * @return (boolean) False if value was not updated and true if value was updated.
532 - */
533 - public static function update_user_option( $option_name, $option_value ) {
534 - $user = wp_get_current_user();
535 - if ( $user ) {
536 - return update_user_option( $user->ID, $option_name, $option_value );
537 - }
538 - return false;
539 - }
638 + return http_build_query( $data, '', '&' );
639 + }
540 640
541 - /**
542 - * Method remove_preslash_spaces()
543 - *
544 - * Remove spaces before slashes.
545 - *
546 - * @param string $text String to strip.
547 - *
548 - * @return string $text Cleaned string.
549 - */
550 - public static function remove_preslash_spaces( $text ) {
551 - while ( stristr( $text, ' /' ) ) {
552 - $text = str_replace( ' /', '/', $text );
553 - }
641 + return null;
642 + }
554 643
555 - return $text;
556 - }
644 + /*
645 + * $websites: Expected array of objects ($website->id, $website->url, ... returned by MainWP_DB) indexed by the object->id
646 + * $what: What function needs to be called - defined in the mainwpplugin
647 + * $params: (Optional) array(key => value, key => value);
648 + * $handler: Name of a function to be called:
649 + * function handler($data, $website, &$output) {}
650 + * the $data = data returned by the request, $website = website object returned by MainWP_DB
651 + * $output has to be filled in by the handler-function - it is used as an output variable!
652 + */
557 653
558 - /**
559 - * Method remove_http_prefix()
560 - *
561 - * Remove http prefixes from given url.
562 - *
563 - * @param mixed $pUrl Given URL.
564 - * @param bool $pTrimSlashes Whether or not to trim slashes. Default is false.
565 - *
566 - * @return string Trimmed URL.
567 - */
568 - public static function remove_http_prefix( $pUrl, $pTrimSlashes = false ) {
569 - return str_replace( array( 'http:' . ( $pTrimSlashes ? '//' : '' ), 'https:' . ( $pTrimSlashes ? '//' : '' ) ), array( '', '' ), $pUrl );
570 - }
654 + static function fetchUrlsAuthed( &$websites, $what, $params = null, $handler, &$output, $whatPage = null,
655 + $others = array() ) {
656 + if ( !is_array( $websites ) || empty( $websites ) ) {
657 + return false;
658 + }
571 659
572 - /**
573 - * Method remove_http_www_prefix()
574 - *
575 - * Remove 'www.' from given URL.
576 - *
577 - * @param mixed $pUrl Given URL.
578 - *
579 - * @return string Cleaned URL.
580 - */
581 - public static function remove_http_www_prefix( $pUrl ) {
582 - $pUrl = static::remove_http_prefix( $pUrl, true );
583 - if ( static::starts_with( strtolower( $pUrl ), 'www.' ) ) {
584 - $pUrl = substr( $pUrl, 4 );
585 - }
586 - return $pUrl;
587 - }
660 + $chunkSize = 10;
661 + if ( count( $websites ) > $chunkSize ) {
662 + $total = count( $websites );
663 + $loops = ceil( $total / $chunkSize );
664 + for ( $i = 0; $i < $loops; $i ++ ) {
665 + $newSites = array_slice( $websites, $i * $chunkSize, $chunkSize, true );
666 + self::fetchUrlsAuthed( $newSites, $what, $params, $handler, $output, $whatPage, $others );
667 + sleep( 5 );
668 + }
588 669
589 - /**
590 - * Method sanitize_file_name()
591 - *
592 - * Sanitize file names.
593 - *
594 - * @param mixed $filename File name to sanitize.
595 - *
596 - * @return string Sanitized filename.
597 - */
598 - public static function sanitize_file_name( $filename ) {
599 - $filename = str_replace( array( '|', '/', '\\', ' ', ':' ), array( '-', '-', '-', '-', '-' ), $filename );
600 - return sanitize_file_name( $filename );
601 - }
670 + return false;
671 + }
602 672
673 + $debug = false;
674 + if ( $debug ) {
675 + $agent = 'Mozilla/5.0 (compatible; MainWP/' . MainWP_System::$version . '; +http://mainwp.com)';
603 676
677 + $timeout = 20 * 60 * 60; //20 minutes
604 678
605 - /**
606 - * Method esc_content()
607 - *
608 - * Escape content,
609 - * allowed content (a,href,title,br,em,strong,p,hr,ul,ol,li,h1,h2 ... ).
610 - *
611 - * @param mixed $content Content to escape.
612 - * @param string $type Type of content. Default = note.
613 - * @param mixed $more_allowed input allowed tags - options.
614 - *
615 - * @return string Filtered content containing only the allowed HTML.
616 - */
617 - public static function esc_content( $content, $type = 'note', $more_allowed = array() ) {
618 - if ( ! is_string( $content ) ) {
619 - return $content;
620 - }
679 + $handleToWebsite = array();
680 + $requestUrls = array();
681 + $requestHandles = array();
621 682
622 - if ( 'note' === $type ) {
683 + $dirs = self::getMainWPDir();
684 + $cookieDir = $dirs[ 0 ] . 'cookies';
685 + if ( !@is_dir( $cookieDir ) ) {
686 + @mkdir( $cookieDir, 0777, true );
687 + }
623 688
624 - $allowed_html = array(
625 - 'a' => array(
626 - 'href' => array(),
627 - 'title' => array(),
628 - ),
629 - 'br' => array(),
630 - 'em' => array(),
631 - 'strong' => array(),
632 - 'p' => array(),
633 - 'hr' => array(),
634 - 'ul' => array(),
635 - 'ol' => array(),
636 - 'li' => array(),
637 - 'h1' => array(),
638 - 'h2' => array(),
639 - );
689 + if ( !file_exists( $cookieDir . '/.htaccess' ) ) {
690 + $file_htaccess = @fopen( $cookieDir . '/.htaccess', 'w+' );
691 + @fwrite( $file_htaccess, 'deny from all' );
692 + @fclose( $file_htaccess );
693 + }
640 694
641 - if ( is_array( $more_allowed ) && ! empty( $more_allowed ) ) {
642 - $allowed_html = array_merge( $allowed_html, $more_allowed );
643 - }
695 + if ( !file_exists( $cookieDir . '/index.php' ) ) {
696 + $file_index = @fopen( $cookieDir . '/index.php', 'w+' );
697 + @fclose( $file_index );
698 + }
644 699
645 - $content = wp_kses( $content, $allowed_html );
700 + foreach ( $websites as $website ) {
701 + $url = $website->url;
702 + if ( substr( $url, - 1 ) != '/' ) {
703 + $url .= '/';
704 + }
646 705
647 - } elseif ( 'mixed' === $type ) {
706 + if ( strpos( $url, 'wp-admin' ) === false ) {
707 + $url .= 'wp-admin/';
708 + }
648 709
649 - $allowed_html = array(
650 - 'a' => array(
651 - 'href' => array(),
652 - 'title' => array(),
653 - 'class' => array(),
654 - 'onclick' => array(),
655 - ),
656 - 'img' => array(
657 - 'src' => array(),
658 - 'title' => array(),
659 - 'class' => array(),
660 - 'onclick' => array(),
661 - 'alt' => array(),
662 - 'width' => array(),
663 - 'height' => array(),
664 - 'sizes' => array(),
665 - 'srcset' => array(),
666 - 'usemap' => array(),
667 - ),
668 - 'br' => array(),
669 - 'em' => array(),
670 - 'strong' => array(),
671 - 'p' => array(),
672 - 'hr' => array(),
673 - 'ul' => array(
674 - 'style' => array(),
675 - ),
676 - 'ol' => array(),
677 - 'li' => array(),
678 - 'h1' => array(),
679 - 'h2' => array(),
680 - 'head' => array(),
681 - 'html' => array(
682 - 'lang' => array(),
683 - ),
684 - 'meta' => array(
685 - 'name' => array(),
686 - 'http-equiv' => array(),
687 - 'content' => array(),
688 - 'charset' => array(),
689 - ),
690 - 'title' => array(),
691 - 'body' => array(
692 - 'style' => array(),
693 - ),
694 - 'span' => array(
695 - 'id' => array(),
696 - 'style' => array(),
697 - 'class' => array(),
698 - ),
699 - 'form' => array(
700 - 'id' => array(),
701 - 'method' => array(),
702 - 'action' => array(),
703 - 'onsubmit' => array(),
704 - ),
705 - 'table' => array(
706 - 'class' => array(),
707 - ),
708 - 'thead' => array(
709 - 'class' => array(),
710 - ),
711 - 'tbody' => array(
712 - 'class' => array(),
713 - ),
714 - 'tr' => array(
715 - 'id' => array(),
716 - ),
717 - 'td' => array(
718 - 'class' => array(),
719 - ),
720 - 'div' => array(
721 - 'id' => array(),
722 - 'style' => array(),
723 - 'class' => array(),
724 - ),
725 - 'input' => array(
726 - 'type' => array(),
727 - 'name' => array(),
728 - 'class' => array(),
729 - 'value' => array(),
730 - 'onclick' => array(),
731 - ),
732 - 'button' => array(
733 - 'type' => array(),
734 - 'name' => array(),
735 - 'value' => array(),
736 - 'class' => array(),
737 - 'title' => array(),
738 - 'onclick' => array(),
739 - ),
740 - );
710 + if ( $whatPage != null ) {
711 + $url .= $whatPage;
712 + } else {
713 + $url .= 'admin-ajax.php';
714 + }
741 715
742 - if ( is_array( $more_allowed ) && ! empty( $more_allowed ) ) {
743 - $allowed_html = array_merge( $allowed_html, $more_allowed );
744 - }
716 + if ( property_exists( $website, 'http_user' ) )
717 + $http_user = $website->http_user;
718 + if ( property_exists( $website, 'http_pass' ) )
719 + $http_pass = $website->http_pass;
745 720
746 - $content = wp_kses( $content, $allowed_html );
747 - } else {
748 - $content = wp_kses_post( $content );
749 - }
721 + $_new_post = null;
722 + if ( isset( $params ) && isset( $params[ 'new_post' ] ) ) {
723 + $_new_post = $params[ 'new_post' ];
724 + //hook for extension: boilerplate ...
725 + $params = apply_filters( 'mainwp-pre-posting-posts', ( is_array( $params ) ? $params : array() ), (object) array(
726 + 'id' => $website->id,
727 + 'url' => $website->url,
728 + 'name' => $website->name,
729 + ) );
730 + }
750 731
751 - return $content;
752 - }
732 + $ch = curl_init();
753 733
754 - /**
755 - * Method esc_mixed_content()
756 - *
757 - * Escape mixed content,
758 - * allowed content (a,href,title,br,em,strong,p,hr,ul,ol,li,h1,h2 ... ).
759 - *
760 - * @param mixed $data data to escape.
761 - * @param string $depth Maximum depth to walk through $data. Must be greater than 0.
762 - * @param mixed $more_allowed input allowed tags - options.
763 - *
764 - * @throws \MainWP_Exception Excetpion message.
765 - *
766 - * @return string Filtered content containing only the allowed HTML.
767 - */
768 - public static function esc_mixed_content( $data, $depth, $more_allowed = array() ) { // phpcs:ignore -- NOSONAR - complex.
769 - if ( $depth < 0 ) {
770 - throw new MainWP_Exception( 'Reached depth limit' );
771 - }
734 + // cURL offers really easy proxy support.
735 + $proxy = new WP_HTTP_Proxy();
736 + if ( $proxy->is_enabled() && $proxy->send_through_proxy( $url ) ) {
737 + curl_setopt( $ch, CURLOPT_PROXYTYPE, CURLPROXY_HTTP );
738 + curl_setopt( $ch, CURLOPT_PROXY, $proxy->host() );
739 + curl_setopt( $ch, CURLOPT_PROXYPORT, $proxy->port() );
772 740
773 - if ( is_array( $data ) ) {
774 - $output = array();
775 - foreach ( $data as $id => $el ) {
776 - // Don't forget to sanitize the ID!
777 - if ( is_string( $id ) ) {
778 - $clean_id = static::esc_content( $id, 'mixed', $more_allowed );
779 - } else {
780 - $clean_id = $id;
741 + if ( $proxy->use_authentication() ) {
742 + curl_setopt( $ch, CURLOPT_PROXYAUTH, CURLAUTH_ANY );
743 + curl_setopt( $ch, CURLOPT_PROXYUSERPWD, $proxy->authentication() );
744 + }
745 + }
746 +
747 + //For WPE upgrades we require cookies too, for normal WPE syncing we do not require cookies, messes up the connection
748 + if ( ( $website != null ) && ( ( property_exists($website, 'wpe') && $website->wpe != 1 ) || ( isset( $others['upgrade'] ) && ( $others['upgrade'] === true ) ) ) ) {
749 + $cookieFile = $cookieDir . '/' . sha1( sha1( 'mainwp' . LOGGED_IN_SALT . $website->id ) . NONCE_SALT . 'WP_Cookie' );
750 + if ( !file_exists( $cookieFile ) ) {
751 + @file_put_contents( $cookieFile, '' );
752 + }
753 +
754 + if ( file_exists( $cookieFile ) ) {
755 + @chmod( $cookieFile, 0644 );
756 + @curl_setopt( $ch, CURLOPT_COOKIEJAR, $cookieFile );
757 + @curl_setopt( $ch, CURLOPT_COOKIEFILE, $cookieFile );
758 + }
759 + }
760 +
761 + @curl_setopt( $ch, CURLOPT_URL, $url );
762 + @curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
763 + @curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, true );
764 + @curl_setopt( $ch, CURLOPT_POST, true );
765 + $postdata = MainWP_Utility::getPostDataAuthed( $website, $what, $params );
766 + @curl_setopt( $ch, CURLOPT_POSTFIELDS, $postdata );
767 + @curl_setopt( $ch, CURLOPT_CONNECTTIMEOUT, 10 );
768 + @curl_setopt( $ch, CURLOPT_USERAGENT, $agent );
769 + @curl_setopt( $ch, CURLOPT_ENCODING, 'none'); // to fix
770 + if ( !empty( $http_user ) && !empty( $http_pass ) ) {
771 + $http_pass = stripslashes($http_pass); // to fix
772 + curl_setopt( $ch, CURLOPT_USERPWD, "$http_user:$http_pass" );
773 + }
774 +
775 + $ssl_verifyhost = false;
776 + $verifyCertificate = isset( $website->verify_certificate ) ? $website->verify_certificate : null;
777 + if ( $verifyCertificate !== null ) {
778 + if ( $verifyCertificate == 1 ) {
779 + $ssl_verifyhost = true;
780 + } else if ( $verifyCertificate == 2 ) { // use global setting
781 + if ( ( ( get_option( 'mainwp_sslVerifyCertificate' ) === false ) || ( get_option( 'mainwp_sslVerifyCertificate' ) == 1 ) ) ) {
782 + $ssl_verifyhost = true;
783 + }
784 + }
785 + } else {
786 + if ( ( ( get_option( 'mainwp_sslVerifyCertificate' ) === false ) || ( get_option( 'mainwp_sslVerifyCertificate' ) == 1 ) ) ) {
787 + $ssl_verifyhost = true;
788 + }
789 + }
790 +
791 + if ( $ssl_verifyhost ) {
792 + @curl_setopt( $ch, CURLOPT_SSL_VERIFYHOST, 2 );
793 + @curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, true );
794 + } else {
795 + @curl_setopt( $ch, CURLOPT_SSL_VERIFYHOST, false );
796 + @curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, false );
797 + }
798 +
799 + @curl_setopt( $ch, CURLOPT_SSLVERSION, $website->ssl_version );
800 + @curl_setopt( $ch, CURLOPT_HTTPHEADER, array( "X-Requested-With: XMLHttpRequest" ) );
801 + @curl_setopt( $ch, CURLOPT_REFERER, get_option( 'siteurl' ));
802 +
803 + $force_use_ipv4 = false;
804 + $forceUseIPv4 = isset( $website->force_use_ipv4 ) ? $website->force_use_ipv4 : null;
805 + if ( $forceUseIPv4 !== null ) {
806 + if ( $forceUseIPv4 == 1 ) {
807 + $force_use_ipv4 = true;
808 + } else if ( $forceUseIPv4 == 2 ) { // use global setting
809 + if ( get_option( 'mainwp_forceUseIPv4' ) == 1 ) {
810 + $force_use_ipv4 = true;
811 + }
812 + }
813 + } else {
814 + if ( get_option( 'mainwp_forceUseIPv4' ) == 1 ) {
815 + $force_use_ipv4 = true;
816 + }
817 + }
818 +
819 + if ( $force_use_ipv4 ) {
820 + if ( defined( 'CURLOPT_IPRESOLVE' ) AND defined( 'CURL_IPRESOLVE_V4' ) ) {
821 + @curl_setopt( $ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4 );
822 + }
823 + }
824 +
825 + @curl_setopt( $ch, CURLOPT_TIMEOUT, $timeout ); //20minutes
826 + if ( version_compare( phpversion(), '5.3.0' ) >= 0 || !ini_get( 'safe_mode' ) ) {
827 + @set_time_limit( $timeout );
828 + } //20minutes
829 + @ini_set( 'max_execution_time', $timeout );
830 +
831 + $handleToWebsite[ self::get_resource_id( $ch ) ] = $website;
832 + $requestUrls[ self::get_resource_id( $ch ) ] = $website->url;
833 + $requestHandles[ self::get_resource_id( $ch ) ] = $ch;
834 +
835 + if ( $_new_post != null ) {
836 + $params[ 'new_post' ] = $_new_post;
837 + } // reassign new_post
838 + }
839 +
840 + foreach ( $requestHandles as $id => $ch ) {
841 + $website = &$handleToWebsite[ self::get_resource_id( $ch ) ];
842 +
843 + $identifier = null;
844 + $semLock = '103218'; //SNSyncLock
845 + //Lock
846 + $identifier = MainWP_Utility::getLockIdentifier( $semLock );
847 +
848 + //Check the delays
849 + //In MS
850 + $minimumDelay = ( ( get_option( 'mainwp_minimumDelay' ) === false ) ? 200 : get_option( 'mainwp_minimumDelay' ) );
851 + if ( $minimumDelay > 0 ) {
852 + $minimumDelay = $minimumDelay / 1000;
853 + }
854 + $minimumIPDelay = ( ( get_option( 'mainwp_minimumIPDelay' ) === false ) ? 400 : get_option( 'mainwp_minimumIPDelay' ) );
855 + if ( $minimumIPDelay > 0 ) {
856 + $minimumIPDelay = $minimumIPDelay / 1000;
857 + }
858 +
859 + MainWP_Utility::endSession();
860 + $delay = true;
861 + while ( $delay ) {
862 + MainWP_Utility::lock( $identifier );
863 +
864 + if ( $minimumDelay > 0 ) {
865 + //Check last request overall
866 + $lastRequest = MainWP_DB::Instance()->getLastRequestTimestamp();
867 + if ( $lastRequest > ( ( microtime( true ) ) - $minimumDelay ) ) {
868 + //Delay!
869 + MainWP_Utility::release( $identifier );
870 + usleep( ( $minimumDelay - ( ( microtime( true ) ) - $lastRequest ) ) * 1000 * 1000 );
871 + continue;
872 + }
873 + }
874 +
875 + if ( $minimumIPDelay > 0 && $website != null ) {
876 + //Get ip of this site url
877 + $ip = MainWP_DB::Instance()->getWPIp( $website->id );
878 +
879 + if ( $ip != null && $ip != '' ) {
880 + //Check last request for this site
881 + $lastRequest = MainWP_DB::Instance()->getLastRequestTimestamp( $ip );
882 +
883 + //Check last request for this subnet?
884 + if ( $lastRequest > ( ( microtime( true ) ) - $minimumIPDelay ) ) {
885 + //Delay!
886 + MainWP_Utility::release( $identifier );
887 + usleep( ( $minimumIPDelay - ( ( microtime( true ) ) - $lastRequest ) ) * 1000 * 1000 );
888 + continue;
889 + }
890 + }
891 + }
892 +
893 + $delay = false;
894 + }
895 +
896 + //Check the simultaneous requests
897 + $maximumRequests = ( ( get_option( 'mainwp_maximumRequests' ) === false ) ? 4 : get_option( 'mainwp_maximumRequests' ) );
898 + $maximumIPRequests = ( ( get_option( 'mainwp_maximumIPRequests' ) === false ) ? 1 : get_option( 'mainwp_maximumIPRequests' ) );
899 +
900 + $first = true;
901 + $delay = true;
902 + while ( $delay ) {
903 + if ( !$first ) {
904 + MainWP_Utility::lock( $identifier );
905 + } else {
906 + $first = false;
907 + }
908 +
909 + //Clean old open requests (may have timed out or something..)
910 + MainWP_DB::Instance()->closeOpenRequests();
911 +
912 + if ( $maximumRequests > 0 ) {
913 + $nrOfOpenRequests = MainWP_DB::Instance()->getNrOfOpenRequests();
914 + if ( $nrOfOpenRequests >= $maximumRequests ) {
915 + //Delay!
916 + MainWP_Utility::release( $identifier );
917 + //Wait 200ms
918 + usleep( 200000 );
919 + continue;
920 + }
921 + }
922 +
923 + if ( $maximumIPRequests > 0 && $website != null ) {
924 + //Get ip of this site url
925 + $ip = MainWP_DB::Instance()->getWPIp( $website->id );
926 +
927 + if ( $ip != null && $ip != '' ) {
928 + $nrOfOpenRequests = MainWP_DB::Instance()->getNrOfOpenRequests( $ip );
929 + if ( $nrOfOpenRequests >= $maximumIPRequests ) {
930 + //Delay!
931 + MainWP_Utility::release( $identifier );
932 + //Wait 200ms
933 + usleep( 200000 );
934 + continue;
935 + }
936 + }
937 + }
938 +
939 + $delay = false;
940 + }
941 +
942 +
943 + if ( $website != null ) {
944 + //Log the start of this request!
945 + MainWP_DB::Instance()->insertOrUpdateRequestLog( $website->id, null, microtime( true ), null );
946 + }
947 +
948 + if ( $identifier != null ) {
949 + //Unlock
950 + MainWP_Utility::release( $identifier );
951 + }
952 +
953 + $data = curl_exec( $ch );
954 +
955 + if ( $website != null ) {
956 + MainWP_DB::Instance()->insertOrUpdateRequestLog( $website->id, $ip, null, microtime( true ) );
957 + }
958 +
959 + if ( $handler != null ) {
960 + call_user_func_array( $handler, array( $data, $website, &$output ) );
961 + }
962 + }
963 +
964 + return true;
965 + }
966 +
967 + //$agent = 'Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)';
968 + $agent = 'Mozilla/5.0 (compatible; MainWP/' . MainWP_System::$version . '; +http://mainwp.com)';
969 + $mh = curl_multi_init();
970 +
971 + $timeout = 20 * 60 * 60; //20 minutes
972 +
973 + $disabled_functions = ini_get( 'disable_functions' );
974 + $handleToWebsite = array();
975 + $requestUrls = array();
976 + $requestHandles = array();
977 +
978 + $dirs = self::getMainWPDir();
979 + $cookieDir = $dirs[ 0 ] . 'cookies';
980 + if ( !@is_dir( $cookieDir ) ) {
981 + @mkdir( $cookieDir, 0777, true );
982 + }
983 +
984 + if ( !file_exists( $cookieDir . '/.htaccess' ) ) {
985 + $file_htaccess = @fopen( $cookieDir . '/.htaccess', 'w+' );
986 + @fwrite( $file_htaccess, 'deny from all' );
987 + @fclose( $file_htaccess );
988 + }
989 +
990 + if ( !file_exists( $cookieDir . '/index.php' ) ) {
991 + $file_index = @fopen( $cookieDir . '/index.php', 'w+' );
992 + @fclose( $file_index );
993 + }
994 +
995 + foreach ( $websites as $website ) {
996 + $url = $website->url;
997 + if ( substr( $url, - 1 ) != '/' ) {
998 + $url .= '/';
999 + }
1000 +
1001 + if ( strpos( $url, 'wp-admin' ) === false ) {
1002 + $url .= 'wp-admin/';
1003 + }
1004 +
1005 + if ( $whatPage != null ) {
1006 + $url .= $whatPage;
1007 + } else {
1008 + $url .= 'admin-ajax.php';
1009 + }
1010 +
1011 + if ( property_exists( $website, 'http_user' ) )
1012 + $http_user = $website->http_user;
1013 + if ( property_exists( $website, 'http_pass' ) )
1014 + $http_pass = $website->http_pass;
1015 +
1016 + $_new_post = null;
1017 + if ( isset( $params ) && isset( $params[ 'new_post' ] ) ) {
1018 + $_new_post = $params[ 'new_post' ];
1019 + $params = apply_filters( 'mainwp-pre-posting-posts', ( is_array( $params ) ? $params : array() ), (object) array(
1020 + 'id' => $website->id,
1021 + 'url' => $website->url,
1022 + 'name' => $website->name,
1023 + ) );
1024 + }
1025 +
1026 + $ch = curl_init();
1027 +
1028 + // cURL offers really easy proxy support.
1029 + $proxy = new WP_HTTP_Proxy();
1030 + if ( $proxy->is_enabled() && $proxy->send_through_proxy( $url ) ) {
1031 + curl_setopt( $ch, CURLOPT_PROXYTYPE, CURLPROXY_HTTP );
1032 + curl_setopt( $ch, CURLOPT_PROXY, $proxy->host() );
1033 + curl_setopt( $ch, CURLOPT_PROXYPORT, $proxy->port() );
1034 +
1035 + if ( $proxy->use_authentication() ) {
1036 + curl_setopt( $ch, CURLOPT_PROXYAUTH, CURLAUTH_ANY );
1037 + curl_setopt( $ch, CURLOPT_PROXYUSERPWD, $proxy->authentication() );
1038 + }
1039 + }
1040 +
1041 + //For WPE upgrades we require cookies too, for normal WPE syncing we do not require cookies, messes up the connection
1042 + if ( ( $website != null ) && ( ( property_exists($website, 'wpe') && $website->wpe != 1 ) || ( isset( $others[ 'upgrade' ] ) && ( $others[ 'upgrade' ] === true ) ) ) ) {
1043 + $cookieFile = $cookieDir . '/' . sha1( sha1( 'mainwp' . LOGGED_IN_SALT . $website->id ) . NONCE_SALT . 'WP_Cookie' );
1044 + if ( !file_exists( $cookieFile ) ) {
1045 + @file_put_contents( $cookieFile, '' );
1046 + }
1047 +
1048 + if ( file_exists( $cookieFile ) ) {
1049 + @chmod( $cookieFile, 0644 );
1050 + @curl_setopt( $ch, CURLOPT_COOKIEJAR, $cookieFile );
1051 + @curl_setopt( $ch, CURLOPT_COOKIEFILE, $cookieFile );
1052 + }
1053 + }
1054 +
1055 + @curl_setopt( $ch, CURLOPT_URL, $url );
1056 + @curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
1057 + @curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, true );
1058 + @curl_setopt( $ch, CURLOPT_POST, true );
1059 + $postdata = MainWP_Utility::getPostDataAuthed( $website, $what, $params );
1060 + @curl_setopt( $ch, CURLOPT_POSTFIELDS, $postdata );
1061 + @curl_setopt( $ch, CURLOPT_CONNECTTIMEOUT, 10 );
1062 + @curl_setopt( $ch, CURLOPT_USERAGENT, $agent );
1063 + @curl_setopt( $ch, CURLOPT_ENCODING, 'none'); // to fix
1064 + if ( !empty( $http_user ) && !empty( $http_pass ) ) {
1065 + $http_pass = stripslashes($http_pass); // to fix
1066 + curl_setopt( $ch, CURLOPT_USERPWD, "$http_user:$http_pass" );
1067 + }
1068 +
1069 + $ssl_verifyhost = false;
1070 + $verifyCertificate = isset( $website->verify_certificate ) ? $website->verify_certificate : null;
1071 + if ( $verifyCertificate !== null ) {
1072 + if ( $verifyCertificate == 1 ) {
1073 + $ssl_verifyhost = true;
1074 + } else if ( $verifyCertificate == 2 ) { // use global setting
1075 + if ( ( ( get_option( 'mainwp_sslVerifyCertificate' ) === false ) || ( get_option( 'mainwp_sslVerifyCertificate' ) == 1 ) ) ) {
1076 + $ssl_verifyhost = true;
1077 + }
1078 + }
1079 + } else {
1080 + if ( ( ( get_option( 'mainwp_sslVerifyCertificate' ) === false ) || ( get_option( 'mainwp_sslVerifyCertificate' ) == 1 ) ) ) {
1081 + $ssl_verifyhost = true;
1082 + }
1083 + }
1084 +
1085 + if ( $ssl_verifyhost ) {
1086 + @curl_setopt( $ch, CURLOPT_SSL_VERIFYHOST, 2 );
1087 + @curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, true );
1088 + } else {
1089 + @curl_setopt( $ch, CURLOPT_SSL_VERIFYHOST, false );
1090 + @curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, false );
1091 + }
1092 +
1093 + @curl_setopt( $ch, CURLOPT_SSLVERSION, $website->ssl_version );
1094 +
1095 + @curl_setopt( $ch, CURLOPT_TIMEOUT, $timeout ); //20minutes
1096 + if ( version_compare( phpversion(), '5.3.0' ) >= 0 || !ini_get( 'safe_mode' ) ) {
1097 + @set_time_limit( $timeout );
1098 + } //20minutes
1099 + @ini_set( 'max_execution_time', $timeout );
1100 +
1101 + if ( empty( $disabled_functions ) || ( stristr( $disabled_functions, 'curl_multi_exec' ) === false ) ) {
1102 + @curl_multi_add_handle( $mh, $ch );
1103 + }
1104 +
1105 + $handleToWebsite[ self::get_resource_id( $ch ) ] = $website;
1106 + $requestUrls[ self::get_resource_id( $ch ) ] = $website->url;
1107 + $requestHandles[ self::get_resource_id( $ch ) ] = $ch;
1108 +
1109 + if ( $_new_post != null ) {
1110 + $params[ 'new_post' ] = $_new_post;
1111 + } // reassign new_post
1112 + }
1113 +
1114 + if ( empty( $disabled_functions ) || ( stristr( $disabled_functions, 'curl_multi_exec' ) === false ) ) {
1115 + $lastRun = 0;
1116 + do {
1117 + if ( time() - $lastRun > 20 ) {
1118 + @set_time_limit( $timeout ); //reset timer..
1119 + $lastRun = time();
1120 + }
1121 +
1122 + curl_multi_exec( $mh, $running ); //Execute handlers
1123 + while ( $info = curl_multi_info_read( $mh ) ) {
1124 + $data = curl_multi_getcontent( $info[ 'handle' ] );
1125 + $contains = ( preg_match( '/<mainwp>(.*)<\/mainwp>/', $data, $results ) > 0 );
1126 + curl_multi_remove_handle( $mh, $info[ 'handle' ] );
1127 +
1128 + if ( !$contains && isset( $requestUrls[ self::get_resource_id( $info[ 'handle' ] ) ] ) ) {
1129 + curl_setopt( $info[ 'handle' ], CURLOPT_URL, $requestUrls[ self::get_resource_id( $info[ 'handle' ] ) ] );
1130 + curl_multi_add_handle( $mh, $info[ 'handle' ] );
1131 + unset( $requestUrls[ self::get_resource_id( $info[ 'handle' ] ) ] );
1132 + $running ++;
1133 + continue;
1134 + }
1135 +
1136 + if ( $handler != null ) {
1137 + $site = &$handleToWebsite[ self::get_resource_id( $info[ 'handle' ] ) ];
1138 + call_user_func_array( $handler, array( $data, $site, &$output ) );
1139 + }
1140 +
1141 + unset( $handleToWebsite[ self::get_resource_id( $info[ 'handle' ] ) ] );
1142 + if ( gettype( $info[ 'handle' ] ) == 'resource' ) {
1143 + curl_close( $info[ 'handle' ] );
1144 + }
1145 + unset( $info[ 'handle' ] );
1146 + }
1147 + usleep( 10000 );
1148 + } while ( $running > 0 );
1149 +
1150 + curl_multi_close( $mh );
1151 + } else {
1152 + foreach ( $requestHandles as $id => $ch ) {
1153 + $data = curl_exec( $ch );
1154 +
1155 + if ( $handler != null ) {
1156 + $site = &$handleToWebsite[ self::get_resource_id( $ch ) ];
1157 + call_user_func_array( $handler, array( $data, $site, &$output ) );
1158 + }
1159 + }
1160 + }
1161 +
1162 + return true;
1163 + }
1164 +
1165 + static function fetchUrlAuthed( &$website, $what, $params = null, $checkConstraints = false, $pForceFetch = false,
1166 + $pRetryFailed = true, $rawResponse = null ) {
1167 + if ( $params == null ) {
1168 + $params = array();
1169 + }
1170 +
1171 + $others = array('force_use_ipv4' => $website->force_use_ipv4, 'upgrade' => ( $what == 'upgradeplugintheme' || $what == 'upgrade' || $what == 'upgradetranslation' ) );
1172 +
1173 + $request_update = false;
1174 + // detect premiums plugins/themes update
1175 + if ( $what == 'stats' || ( $what == 'upgradeplugintheme' && isset( $params['type'] )) ) {
1176 +
1177 + $update_type = '';
1178 +
1179 + $check_premi_plugins = $check_premi_themes = array();
1180 +
1181 + if ($what == 'stats') {
1182 + if ( $website->plugins != '' ) {
1183 + $check_premi_plugins = json_decode( $website->plugins, 1 );
781 1184 }
1185 + if ( $website->themes != '' ) {
1186 + $check_premi_themes = @json_decode( $website->themes, 1 );
1187 + }
1188 + } else if ( $what == 'upgradeplugintheme' ) {
782 1189
783 - // Check the element type, so that we're only recursing if we really have to.
784 - if ( is_array( $el ) || is_object( $el ) ) {
785 - $output[ $clean_id ] = static::esc_mixed_content( $el, $depth - 1 );
786 - } elseif ( is_string( $el ) ) {
787 - $output[ $clean_id ] = static::esc_content( $el, 'mixed', $more_allowed );
788 - } else {
789 - $output[ $clean_id ] = $el;
1190 + $update_type = (isset( $params['type'] )) ? $params['type'] : '';
1191 + if ( $update_type == 'plugin' ) {
1192 + if ( $website->plugins != '' ) {
1193 + $check_premi_plugins = json_decode( $website->plugins, 1 );
1194 + }
1195 + } else if ( $update_type == 'theme' ) {
1196 + if ( $website->themes != '' ) {
1197 + $check_premi_themes = @json_decode( $website->themes, 1 );
790 1198 }
791 1199 }
792 - } elseif ( is_object( $data ) ) {
793 - $output = new stdClass();
794 - foreach ( $data as $id => $el ) {
795 - if ( is_string( $id ) ) {
796 - $clean_id = static::esc_content( $id, 'mixed', $more_allowed );
797 - } else {
798 - $clean_id = $id;
1200 +
1201 + }
1202 +
1203 + if ( is_array( $check_premi_plugins ) && count( $check_premi_plugins ) > 0 ) {
1204 + if (self::checkPremiumUpdates( $check_premi_plugins, 'plugin' )) {
1205 + // detect plugin
1206 + self::try_to_detect_premiums_update( $website, 'plugin' );
799 1207 }
1208 + }
800 1209
801 - if ( is_array( $el ) || is_object( $el ) ) {
802 - $output->$clean_id = static::esc_mixed_content( $el, $depth - 1, $more_allowed );
803 - } elseif ( is_string( $el ) ) {
804 - $output->$clean_id = static::esc_content( $el, 'mixed', $more_allowed );
805 - } else {
806 - $output->$clean_id = $el;
1210 + if ( is_array( $check_premi_themes ) && count( $check_premi_themes ) > 0 ) {
1211 + if ( self::checkPremiumUpdates( $check_premi_themes, 'theme' ) ) {
1212 + // detect themes
1213 + self::try_to_detect_premiums_update( $website, 'theme' );
807 1214 }
808 1215 }
809 - } elseif ( is_string( $data ) ) {
810 - return static::esc_content( $data, 'mixed', $more_allowed );
811 - } else {
812 - return $data;
1216 +
1217 + if ( $what == 'upgradeplugintheme' ) {
1218 + if ( $update_type == 'plugin' || $update_type == 'theme' ) {
1219 + // request premiums update
1220 + if ( self::checkRequestUpdatePremium( $params['list'], $update_type ) ) {
1221 + self::request_premiums_update( $website, $update_type, $params['list'] );
1222 + $request_update = true;
1223 + }
1224 + }
1225 + }
1226 + }
1227 + // end detect/request update
1228 +
1229 + if (isset($rawResponse) && $rawResponse) {
1230 + $others['raw_response'] = 'yes';
813 1231 }
814 1232
815 - return $output;
816 - }
1233 + $params['optimize'] = ( ( get_option( 'mainwp_optimize' ) == 1 ) ? 1 : 0 );
817 1234
818 - /**
819 - * Method parse_html_error_message()
820 - *
821 - * @param string $error_msg Error message.
822 - *
823 - * @return mixed array|string.
824 - */
825 - public static function parse_html_error_message( $error_msg ) {
826 - // pasing error message that included link html.
827 - preg_match( '/([^\<]*)(<a[^\>]*>)([^\<]*)(<[^\>]*>)(.*)/', $error_msg, $output_array );
828 - if ( is_array( $output_array ) && 6 === count( $output_array ) ) {
829 - preg_match( '/<a href="([^\"]*)"(.*)/', $output_array[2], $link_array );
830 - $link = '';
831 - if ( is_array( $link_array ) && 3 === count( $link_array ) ) {
832 - $link = $link_array[1];
1235 + $updating_website = false;
1236 + $type = $list = '';
1237 + if ( $what == 'upgradeplugintheme' || $what == 'upgrade' || $what == 'upgradetranslation' ) {
1238 + $updating_website = true;
1239 + if ( $what == 'upgradeplugintheme' || $what == 'upgradetranslation' ) {
1240 + $type = $params['type'];
1241 + $list = $params['list'];
1242 + } else {
1243 + $type = 'wp';
1244 + $list = '';
833 1245 }
834 - if ( ! empty( $link ) ) {
835 - return array(
836 - 'el_before' => esc_html( $output_array[1] ),
837 - 'el_link' => esc_html( $link ),
838 - 'el_text' => esc_html( $output_array[3] ),
839 - 'el_after' => esc_html( $output_array[5] ),
840 - );
841 - }
842 1246 }
843 - return $error_msg;
844 - }
845 1247
846 - /**
847 - * Method show_mainwp_message()
848 - *
849 - * Check whenther or not to show the MainWP Message.
850 - *
851 - * @param mixed $type Type of message.
852 - * @param mixed $notice_id Notice ID.
853 - *
854 - * @return boolean true|false.
855 - */
856 - public static function show_mainwp_message( $type, $notice_id ) {
857 - unset( $type );
858 - $status = get_user_option( 'mainwp_notice_saved_status' );
859 - if ( ! is_array( $status ) ) {
860 - $status = array();
1248 + if ($updating_website) {
1249 + do_action( 'mainwp_website_before_updated', $website, $type, $list );
861 1250 }
862 - if ( isset( $status[ $notice_id ] ) ) {
863 - return false;
864 - }
865 - return true;
866 - }
867 1251
868 - /**
869 - * Method get_hide_notice_status()
870 - *
871 - * Check whenther or not to show the MainWP Message.
872 - *
873 - * @param mixed $notice_id Notice ID.
874 - *
875 - * @return mixed true|false|time.
876 - */
877 - public static function get_hide_notice_status( $notice_id ) {
878 - $notices = get_user_option( 'mainwp_notice_saved_status' );
879 - if ( ! is_array( $notices ) ) {
880 - $notices = array();
881 - }
882 - if ( isset( $notices[ $notice_id ] ) ) {
883 - return $notices[ $notice_id ];
884 - }
885 - return false;
886 - }
1252 + $postdata = MainWP_Utility::getPostDataAuthed( $website, $what, $params );
887 1253
888 - /**
889 - * Method get_flash_message()
890 - *
891 - * Get saved flash Message.
892 - *
893 - * @param mixed $message_id Notice ID.
894 - * @param bool $delete True to delete the message after get it.
895 - *
896 - * @return boolean true|false.
897 - */
898 - public static function get_flash_message( $message_id, $delete = true ) {
899 - $flash_messages = get_user_option( 'mainwp_flash_messages' );
900 - if ( ! is_array( $flash_messages ) ) {
901 - $flash_messages = array();
1254 + $information = array();
1255 + if ( ! $request_update ) {
1256 + $information = MainWP_Utility::fetchUrl( $website, $website->url, $postdata, $checkConstraints, $pForceFetch, $website->verify_certificate, $pRetryFailed, $website->http_user, $website->http_pass, $website->ssl_version, $others );
1257 + } else {
1258 + $slug = $params['list'];
1259 + // temporary set it is successful, see function upgradePluginThemeTranslation()
1260 + // need to re-sync to update info
1261 + $information['upgrades'] = array( $slug => 1 );
902 1262 }
903 - if ( ! isset( $flash_messages[ $message_id ] ) ) {
904 - return false;
905 - }
906 - $content = $flash_messages[ $message_id ];
907 - if ( $delete ) {
908 - unset( $flash_messages[ $message_id ] );
909 - static::update_user_option( 'mainwp_flash_messages', $flash_messages );
910 - }
911 - return $content;
912 - }
913 1263
914 - /**
915 - * Method update_flash_message()
916 - *
917 - * Check whenther or not to show the MainWP Message.
918 - *
919 - * @param mixed $message_id Notice ID.
920 - * @param mixed $content Content of message.
921 - *
922 - * @return boolean true|false.
923 - */
924 - public static function update_flash_message( $message_id, $content ) {
925 - $flash_messages = get_user_option( 'mainwp_flash_messages' );
926 - if ( ! is_array( $flash_messages ) ) {
927 - $flash_messages = array();
928 - }
929 - $current = isset( $flash_messages[ $message_id ] ) ? $flash_messages[ $message_id ] : '';
930 - if ( empty( $current ) ) {
931 - $current = $content;
932 - } else {
933 - $current .= '|' . $content;
934 - }
935 - $flash_messages[ $message_id ] = $current;
936 - return static::update_user_option( 'mainwp_flash_messages', $flash_messages );
937 - }
1264 + if ( is_array( $information ) && isset( $information['sync'] ) && ! empty( $information['sync'] ) ) {
1265 + MainWP_Sync::syncInformationArray( $website, $information['sync'] );
1266 + unset( $information['sync'] );
1267 + }
938 1268
939 - /**
940 - * Method array_sort()
941 - *
942 - * Sort given array by given flags.
943 - *
944 - * @param mixed $arr Array to sort.
945 - * @param mixed $key Array key.
946 - * @param string $sort_flag Flags to sort by. Default = SORT_STRING.
947 - */
948 - public static function array_sort( &$arr, $key, $sort_flag = SORT_STRING ) {
949 - $sorter = array();
950 - $ret = array();
951 - reset( $arr );
952 - foreach ( $arr as $ii => $val ) {
953 - $sorter[ $ii ] = $val[ $key ];
954 - }
955 - asort( $sorter, $sort_flag );
956 - foreach ( $sorter as $ii => $val ) {
957 - $ret[ $ii ] = $arr[ $ii ];
958 - }
959 - $arr = $ret;
960 - }
1269 + if ( $updating_website ) {
1270 + do_action( 'mainwp_website_updated', $website, $type, $list, $information );
1271 + if ( 1 == get_option( 'mainwp_check_http_response', 0 ) ) {
1272 + $result = MainWP_Utility::isWebsiteAvailable( $website );
1273 + $http_code = ( is_array($result) && isset( $result['httpCode'] ) ) ? $result['httpCode'] : 0;
1274 + $online_detected = MainWP_Utility::check_ignored_http_code( $http_code );
1275 + MainWP_DB::Instance()->updateWebsiteValues( $website->id, array(
1276 + 'offline_check_result' => $online_detected ? 1 : -1,
1277 + 'offline_checks_last' => time(),
1278 + 'http_response_code' => $http_code
1279 + ) );
961 1280
962 - /**
963 - * Method array_sort_existed_keys()
964 - *
965 - * Sort given array by given flags.
966 - *
967 - * @param mixed $arr Array to sort.
968 - * @param mixed $key Array key.
969 - * @param string $sort_flag Flags to sort by. Default = SORT_STRING.
970 - */
971 - public static function array_sort_existed_keys( &$arr, $key, $sort_flag = SORT_STRING ) {
972 - $sorter = array();
973 - $ret = array();
974 - reset( $arr );
1281 + if ( defined( 'DOING_CRON' ) && DOING_CRON && !$online_detected) {
1282 + $sitesHttpChecks = get_option( 'mainwp_automaticUpdate_httpChecks' );
1283 + if ( !is_array( $sitesHttpChecks ) ) {
1284 + $sitesHttpChecks = array();
1285 + }
975 1286
976 - // get items with $key to sort.
977 - foreach ( $arr as $ii => $val ) {
978 - if ( isset( $val[ $key ] ) ) {
979 - $sorter[ $ii ] = $val[ $key ];
1287 + if ( !in_array( $website->id, $sitesHttpChecks ) ) {
1288 + $sitesHttpChecks[] = $website->id;
1289 + MainWP_Utility::update_option( 'mainwp_automaticUpdate_httpChecks', $sitesHttpChecks );
1290 + }
1291 + }
980 1292 }
981 1293 }
982 - asort( $sorter, $sort_flag );
983 1294
984 - foreach ( $sorter as $ii => $val ) {
985 - $ret[ $ii ] = $arr[ $ii ];
986 - }
1295 + return $information;
1296 + }
987 1297
988 - // asign other items (without $keys).
989 - foreach ( $arr as $ii => $val ) {
990 - if ( ! isset( $val[ $key ] ) ) {
991 - $ret[ $ii ] = $val;
992 - }
993 - }
1298 + static function fetchUrlNotAuthed( $url, $admin, $what, $params = null, $pForceFetch = false,
1299 + $verifyCertificate = null, $http_user = null, $http_pass = null, $sslVersion = 0, $others = array() ) {
1300 + $postdata = MainWP_Utility::getPostDataNotAuthed( $url, $admin, $what, $params );
1301 + $website = null;
994 1302
995 - $arr = $ret;
996 - }
1303 + return MainWP_Utility::fetchUrl( $website, $url, $postdata, false, $pForceFetch, $verifyCertificate, true, $http_user, $http_pass, $sslVersion, $others );
1304 + }
997 1305
998 - /**
999 - * Method numeric_filter()
1000 - *
1001 - * Filter given numeric.
1002 - *
1003 - * @param int $int_num Int number.
1004 - * @return array $arr_ints Array filtered.
1005 - */
1006 - public static function numeric_filter( $int_num ) {
1007 - return ( (string) (int) $int_num === (string) $int_num && 0 < $int_num ) ? $int_num : false;
1008 - }
1306 + static function fetchUrlClean( $url, $postdata ) {
1307 + //$agent = 'Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)';
1308 + $agent = 'Mozilla/5.0 (compatible; MainWP/' . MainWP_System::$version . '; +http://mainwp.com)';
1009 1309
1010 - /**
1011 - * Method array_numeric_filter()
1012 - *
1013 - * Filter given numeric array.
1014 - *
1015 - * @param array $arr_ints Array to filter.
1016 - * @return array $arr_ints Array filtered.
1017 - */
1018 - public static function array_numeric_filter( $arr_ints ) {
1019 - $arr_ints = array_filter(
1020 - $arr_ints,
1021 - function ( $e ) {
1022 - return ( (string) (int) $e === (string) $e && 0 < $e ) ? true : false;
1023 - }
1024 - );
1025 - return $arr_ints;
1026 - }
1310 + $ch = curl_init();
1027 1311
1028 - /**
1029 - * Method enabled_wp_seo()
1030 - *
1031 - * Check if Yoast SEO is enabled.
1032 - *
1033 - * @return boolean true|false.
1034 - */
1035 - public static function enabled_wp_seo() {
1036 - if ( null === static::$enabled_wp_seo ) {
1037 - static::$enabled_wp_seo = is_plugin_active( 'wordpress-seo-extension/wordpress-seo-extension.php' );
1038 - }
1039 - return static::$enabled_wp_seo;
1040 - }
1312 + // cURL offers really easy proxy support.
1313 + $proxy = new WP_HTTP_Proxy();
1314 + if ( $proxy->is_enabled() && $proxy->send_through_proxy( $url ) ) {
1315 + curl_setopt( $ch, CURLOPT_PROXYTYPE, CURLPROXY_HTTP );
1316 + curl_setopt( $ch, CURLOPT_PROXY, $proxy->host() );
1317 + curl_setopt( $ch, CURLOPT_PROXYPORT, $proxy->port() );
1041 1318
1042 - /**
1043 - * Method value_to_string()
1044 - *
1045 - * Value to string.
1046 - *
1047 - * @param mixed $var_value Value to convert to string.
1048 - *
1049 - * @return string Value that has been converted into a string.
1050 - */
1051 - public static function value_to_string( $var_value ) {
1052 - if ( is_array( $var_value ) || is_object( $var_value ) ) {
1053 - //phpcs:ignore -- for debug only
1054 - return print_r( $var_value, true );
1055 - } elseif ( is_string( $var_value ) ) {
1056 - return $var_value;
1057 - }
1058 - return '';
1059 - }
1319 + if ( $proxy->use_authentication() ) {
1320 + curl_setopt( $ch, CURLOPT_PROXYAUTH, CURLAUTH_ANY );
1321 + curl_setopt( $ch, CURLOPT_PROXYUSERPWD, $proxy->authentication() );
1322 + }
1323 + }
1060 1324
1061 - /**
1062 - * Get Health Site value.
1063 - *
1064 - * @param mixed $issue_counts Health site issues.
1065 - *
1066 - * @return array Health status value.
1067 - */
1068 - public static function get_site_health( $issue_counts ) {
1325 + curl_setopt( $ch, CURLOPT_URL, $url );
1326 + curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
1327 + curl_setopt( $ch, CURLOPT_POST, true );
1328 + curl_setopt( $ch, CURLOPT_POSTFIELDS, $postdata );
1329 + curl_setopt( $ch, CURLOPT_USERAGENT, $agent );
1330 + @curl_setopt( $ch, CURLOPT_ENCODING, 'none'); // to fix
1069 1331
1070 - if ( empty( $issue_counts ) ) {
1071 - $issue_counts = array(
1072 - 'good' => 0,
1073 - 'recommended' => 0,
1074 - 'critical' => 0,
1075 - );
1076 - }
1332 + if ( ( ( get_option( 'mainwp_sslVerifyCertificate' ) === false ) || ( get_option( 'mainwp_sslVerifyCertificate' ) == 1 ) ) ) {
1333 + @curl_setopt( $ch, CURLOPT_SSL_VERIFYHOST, 2 );
1334 + @curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, true );
1335 + } else {
1336 + @curl_setopt( $ch, CURLOPT_SSL_VERIFYHOST, false );
1337 + @curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, false );
1338 + }
1077 1339
1078 - $totalTests = intval( $issue_counts['good'] ) + intval( $issue_counts['recommended'] ) + intval( $issue_counts['critical'] ) * 1.5;
1079 - $failedTests = intval( $issue_counts['recommended'] ) * 0.5 + $issue_counts['critical'] * 1.5;
1340 + $data = curl_exec( $ch );
1341 + curl_close( $ch );
1342 + if ( !$data ) {
1343 + throw new Exception( 'HTTPERROR' );
1344 + } else {
1345 + return $data;
1346 + }
1347 + }
1080 1348
1081 - if ( empty( $totalTests ) ) {
1082 - $val = 100;
1083 - } else {
1084 - $val = 100 - ceil( ( $failedTests / $totalTests ) * 100 );
1085 - }
1349 + static function fetchUrl( &$website, $url, $postdata, $checkConstraints = false, $pForceFetch = false,
1350 + $verifyCertificate = null, $pRetryFailed = true, $http_user = null, $http_pass = null, $sslVersion = 0,
1351 + $others = array() ) {
1352 + $start = time();
1086 1353
1087 - if ( 0 > $val ) {
1088 - $val = 0;
1089 - }
1354 + try {
1355 + $tmpUrl = $url;
1356 + if ( substr( $tmpUrl, - 1 ) != '/' ) {
1357 + $tmpUrl .= '/';
1358 + }
1090 1359
1091 - if ( 100 < $val ) {
1092 - $val = 100;
1360 + if ( strpos( $url, 'wp-admin' ) === false ) {
1361 + $tmpUrl .= 'wp-admin/admin-ajax.php';
1362 + }
1363 +
1364 + return self::_fetchUrl( $website, $tmpUrl, $postdata, $checkConstraints, $pForceFetch, $verifyCertificate, $http_user, $http_pass, $sslVersion, $others );
1365 + } catch ( Exception $e ) {
1366 + if ( !$pRetryFailed || ( ( time() - $start ) > 30 ) ) {
1367 + //If more then 30secs past since the initial request, do not retry this!
1368 + throw $e;
1369 + }
1370 +
1371 + try {
1372 + return self::_fetchUrl( $website, $url, $postdata, $checkConstraints, $pForceFetch, $verifyCertificate, $http_user, $http_pass, $sslVersion, $others );
1373 + } catch ( Exception $ex ) {
1374 + throw $e;
1375 + }
1376 + }
1377 + }
1378 +
1379 + static function _fetchUrl( &$website, $url, $postdata, $checkConstraints = false, $pForceFetch = false,
1380 + $verifyCertificate = null, $http_user = null, $http_pass = null, $sslVersion = 0, $others = array() ) {
1381 + //$agent = 'Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)';
1382 + $agent = 'Mozilla/5.0 (compatible; MainWP/' . MainWP_System::$version . '; +http://mainwp.com)';
1383 +
1384 + MainWP_Logger::Instance()->debugForWebsite( $website, '_fetchUrl', 'Request to [' . $url . '] [' . print_r( $postdata, 1 ) . ']' );
1385 +
1386 + if ( !$pForceFetch ) {
1387 + //todo: RS:
1388 + //check if offline
1389 + }
1390 +
1391 + $identifier = null;
1392 + if ( $checkConstraints ) {
1393 + $semLock = '103218'; //SNSyncLock
1394 + //Lock
1395 + $identifier = MainWP_Utility::getLockIdentifier( $semLock );
1396 +
1397 + //Check the delays
1398 + //In MS
1399 + $minimumDelay = ( ( get_option( 'mainwp_minimumDelay' ) === false ) ? 200 : get_option( 'mainwp_minimumDelay' ) );
1400 + if ( $minimumDelay > 0 ) {
1401 + $minimumDelay = $minimumDelay / 1000;
1402 + }
1403 + $minimumIPDelay = ( ( get_option( 'mainwp_minimumIPDelay' ) === false ) ? 1000 : get_option( 'mainwp_minimumIPDelay' ) );
1404 + if ( $minimumIPDelay > 0 ) {
1405 + $minimumIPDelay = $minimumIPDelay / 1000;
1406 + }
1407 +
1408 + MainWP_Utility::endSession();
1409 + $delay = true;
1410 + while ( $delay ) {
1411 + MainWP_Utility::lock( $identifier );
1412 +
1413 + if ( $minimumDelay > 0 ) {
1414 + //Check last request overall
1415 + $lastRequest = MainWP_DB::Instance()->getLastRequestTimestamp();
1416 + if ( $lastRequest > ( ( microtime( true ) ) - $minimumDelay ) ) {
1417 + //Delay!
1418 + MainWP_Utility::release( $identifier );
1419 + usleep( ( $minimumDelay - ( ( microtime( true ) ) - $lastRequest ) ) * 1000 * 1000 );
1420 + continue;
1421 + }
1422 + }
1423 +
1424 + if ( $minimumIPDelay > 0 && $website != null ) {
1425 + //Get ip of this site url
1426 + $ip = MainWP_DB::Instance()->getWPIp( $website->id );
1427 +
1428 + if ( $ip != null && $ip != '' ) {
1429 + //Check last request for this site
1430 + $lastRequest = MainWP_DB::Instance()->getLastRequestTimestamp( $ip );
1431 +
1432 + //Check last request for this subnet?
1433 + if ( $lastRequest > ( ( microtime( true ) ) - $minimumIPDelay ) ) {
1434 + //Delay!
1435 + MainWP_Utility::release( $identifier );
1436 + usleep( ( $minimumIPDelay - ( ( microtime( true ) ) - $lastRequest ) ) * 1000 * 1000 );
1437 + continue;
1438 + }
1439 + }
1440 + }
1441 +
1442 + $delay = false;
1443 + }
1444 +
1445 + //Check the simultaneous requests
1446 + $maximumRequests = ( ( get_option( 'mainwp_maximumRequests' ) === false ) ? 4 : get_option( 'mainwp_maximumRequests' ) );
1447 + $maximumIPRequests = ( ( get_option( 'mainwp_maximumIPRequests' ) === false ) ? 1 : get_option( 'mainwp_maximumIPRequests' ) );
1448 +
1449 + $first = true;
1450 + $delay = true;
1451 + while ( $delay ) {
1452 + if ( !$first ) {
1453 + MainWP_Utility::lock( $identifier );
1454 + } else {
1455 + $first = false;
1456 + }
1457 +
1458 + //Clean old open requests (may have timed out or something..)
1459 + MainWP_DB::Instance()->closeOpenRequests();
1460 +
1461 + if ( $maximumRequests > 0 ) {
1462 + $nrOfOpenRequests = MainWP_DB::Instance()->getNrOfOpenRequests();
1463 + if ( $nrOfOpenRequests >= $maximumRequests ) {
1464 + //Delay!
1465 + MainWP_Utility::release( $identifier );
1466 + //Wait 200ms
1467 + usleep( 200000 );
1468 + continue;
1469 + }
1470 + }
1471 +
1472 + if ( $maximumIPRequests > 0 && $website != null ) {
1473 + //Get ip of this site url
1474 + $ip = MainWP_DB::Instance()->getWPIp( $website->id );
1475 +
1476 + if ( $ip != null && $ip != '' ) {
1477 + $nrOfOpenRequests = MainWP_DB::Instance()->getNrOfOpenRequests( $ip );
1478 + if ( $nrOfOpenRequests >= $maximumIPRequests ) {
1479 + //Delay!
1480 + MainWP_Utility::release( $identifier );
1481 + //Wait 200ms
1482 + usleep( 200000 );
1483 + continue;
1484 + }
1485 + }
1486 + }
1487 +
1488 + $delay = false;
1489 + }
1490 + }
1491 +
1492 + if ( $website != null ) {
1493 + //Log the start of this request!
1494 + MainWP_DB::Instance()->insertOrUpdateRequestLog( $website->id, null, microtime( true ), null );
1495 + }
1496 +
1497 + if ( $identifier != null ) {
1498 + //Unlock
1499 + MainWP_Utility::release( $identifier );
1500 + }
1501 +
1502 + $dirs = self::getMainWPDir();
1503 + $cookieDir = $dirs[ 0 ] . 'cookies';
1504 + if ( !@is_dir( $cookieDir ) ) {
1505 + @mkdir( $cookieDir, 0777, true );
1506 + }
1507 +
1508 + if ( !file_exists( $cookieDir . '/.htaccess' ) ) {
1509 + $file_htaccess = @fopen( $cookieDir . '/.htaccess', 'w+' );
1510 + @fwrite( $file_htaccess, 'deny from all' );
1511 + @fclose( $file_htaccess );
1512 + }
1513 +
1514 + if ( !file_exists( $cookieDir . '/index.php' ) ) {
1515 + $file_index = @fopen( $cookieDir . '/index.php', 'w+' );
1516 + @fclose( $file_index );
1517 + }
1518 +
1519 + $ch = curl_init();
1520 +
1521 + // cURL offers really easy proxy support.
1522 + $proxy = new WP_HTTP_Proxy();
1523 + if ( $proxy->is_enabled() && $proxy->send_through_proxy( $url ) ) {
1524 + curl_setopt( $ch, CURLOPT_PROXYTYPE, CURLPROXY_HTTP );
1525 + curl_setopt( $ch, CURLOPT_PROXY, $proxy->host() );
1526 + curl_setopt( $ch, CURLOPT_PROXYPORT, $proxy->port() );
1527 +
1528 + if ( $proxy->use_authentication() ) {
1529 + curl_setopt( $ch, CURLOPT_PROXYAUTH, CURLAUTH_ANY );
1530 + curl_setopt( $ch, CURLOPT_PROXYUSERPWD, $proxy->authentication() );
1531 + }
1532 + }
1533 +
1534 + //For WPE upgrades we require cookies too, for normal WPE syncing we do not require cookies, messes up the connection
1535 + if ( ( $website != null ) && ( ( property_exists($website, 'wpe') && $website->wpe != 1 ) || ( isset( $others['upgrade'] ) && ( $others['upgrade'] === true ) ) ) ) {
1536 + $cookieFile = $cookieDir . '/' . sha1( sha1( 'mainwp' . LOGGED_IN_SALT . $website->id ) . NONCE_SALT . 'WP_Cookie' );
1537 + if ( !file_exists( $cookieFile ) ) {
1538 + @file_put_contents( $cookieFile, '' );
1539 + }
1540 +
1541 + if ( file_exists( $cookieFile ) ) {
1542 + @chmod( $cookieFile, 0644 );
1543 + @curl_setopt( $ch, CURLOPT_COOKIEJAR, $cookieFile );
1544 + @curl_setopt( $ch, CURLOPT_COOKIEFILE, $cookieFile );
1545 + }
1546 + }
1547 +
1548 + @curl_setopt( $ch, CURLOPT_URL, $url );
1549 + @curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
1550 + @curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, true );
1551 + @curl_setopt( $ch, CURLOPT_POST, true );
1552 + @curl_setopt( $ch, CURLOPT_POSTFIELDS, $postdata );
1553 + @curl_setopt( $ch, CURLOPT_CONNECTTIMEOUT, 10 );
1554 + @curl_setopt( $ch, CURLOPT_USERAGENT, $agent );
1555 + @curl_setopt( $ch, CURLOPT_ENCODING, 'none'); // to fix
1556 +
1557 + if ( !empty( $http_user ) && !empty( $http_pass ) ) {
1558 + $http_pass = stripslashes($http_pass); // to fix
1559 + @curl_setopt( $ch, CURLOPT_USERPWD, "$http_user:$http_pass" );
1560 + }
1561 +
1562 + $ssl_verifyhost = false;
1563 + if ( $verifyCertificate !== null ) {
1564 + if ( $verifyCertificate == 1 ) {
1565 + $ssl_verifyhost = true;
1566 + } else if ( $verifyCertificate == 2 ) { // use global setting
1567 + if ( ( ( get_option( 'mainwp_sslVerifyCertificate' ) === false ) || ( get_option( 'mainwp_sslVerifyCertificate' ) == 1 ) ) ) {
1568 + $ssl_verifyhost = true;
1569 + }
1570 + }
1571 + } else {
1572 + if ( ( ( get_option( 'mainwp_sslVerifyCertificate' ) === false ) || ( get_option( 'mainwp_sslVerifyCertificate' ) == 1 ) ) ) {
1573 + $ssl_verifyhost = true;
1574 + }
1575 + }
1576 +
1577 + if ( $ssl_verifyhost ) {
1578 + @curl_setopt( $ch, CURLOPT_SSL_VERIFYHOST, 2 );
1579 + @curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, true );
1580 + } else {
1581 + @curl_setopt( $ch, CURLOPT_SSL_VERIFYHOST, false );
1582 + @curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, false );
1583 + }
1584 +
1585 + @curl_setopt( $ch, CURLOPT_SSLVERSION, $sslVersion );
1586 + @curl_setopt( $ch, CURLOPT_HTTPHEADER, array( "X-Requested-With: XMLHttpRequest" ) );
1587 + @curl_setopt( $ch, CURLOPT_REFERER, get_option( 'siteurl' ));
1588 +
1589 + $force_use_ipv4 = false;
1590 + $forceUseIPv4 = isset( $others[ 'force_use_ipv4' ] ) ? $others[ 'force_use_ipv4' ] : null;
1591 + if ( $forceUseIPv4 !== null ) {
1592 + if ( $forceUseIPv4 == 1 ) {
1593 + $force_use_ipv4 = true;
1594 + } else if ( $forceUseIPv4 == 2 ) { // use global setting
1595 + if ( get_option( 'mainwp_forceUseIPv4' ) == 1 ) {
1596 + $force_use_ipv4 = true;
1597 + }
1598 + }
1599 + } else {
1600 + if ( get_option( 'mainwp_forceUseIPv4' ) == 1 ) {
1601 + $force_use_ipv4 = true;
1602 + }
1603 + }
1604 +
1605 + if ( $force_use_ipv4 ) {
1606 + if ( defined( 'CURLOPT_IPRESOLVE' ) AND defined( 'CURL_IPRESOLVE_V4' ) ) {
1607 + @curl_setopt( $ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4 );
1608 + }
1609 + }
1610 +
1611 +
1612 + $timeout = 20 * 60 * 60; //20 minutes
1613 + @curl_setopt( $ch, CURLOPT_TIMEOUT, $timeout );
1614 + if ( version_compare( phpversion(), '5.3.0' ) >= 0 || !ini_get( 'safe_mode' ) ) {
1615 + @set_time_limit( $timeout );
1616 + }
1617 + @ini_set( 'max_execution_time', $timeout );
1618 + MainWP_Utility::endSession();
1619 +
1620 + MainWP_Logger::Instance()->debugForWebsite( $website, '_fetchUrl', 'Executing handlers' );
1621 +
1622 + $disabled_functions = ini_get( 'disable_functions' );
1623 + if ( empty( $disabled_functions ) || ( stristr( $disabled_functions, 'curl_multi_exec' ) === false ) ) {
1624 + $mh = @curl_multi_init();
1625 + @curl_multi_add_handle( $mh, $ch );
1626 +
1627 + $lastRun = 0;
1628 + do {
1629 + if ( time() - $lastRun > 20 ) {
1630 + @set_time_limit( $timeout ); //reset timer..
1631 + $lastRun = time();
1632 + }
1633 + @curl_multi_exec( $mh, $running ); //Execute handlers
1634 + //$ready = curl_multi_select($mh);
1635 + while ( $info = @curl_multi_info_read( $mh ) ) {
1636 + $data = @curl_multi_getcontent( $info[ 'handle' ] );
1637 +
1638 + $http_status = @curl_getinfo( $info[ 'handle' ], CURLINFO_HTTP_CODE );
1639 + $err = @curl_error( $info[ 'handle' ] );
1640 + $real_url = @curl_getinfo( $info[ 'handle' ], CURLINFO_EFFECTIVE_URL );
1641 +
1642 + @curl_multi_remove_handle( $mh, $info[ 'handle' ] );
1643 + }
1644 + usleep( 10000 );
1645 + } while ( $running > 0 );
1646 +
1647 + @curl_multi_close( $mh );
1648 + } else {
1649 + $data = @curl_exec( $ch );
1650 + $http_status = @curl_getinfo( $ch, CURLINFO_HTTP_CODE );
1651 + $err = @curl_error( $ch );
1652 + $real_url = @curl_getinfo( $ch, CURLINFO_EFFECTIVE_URL );
1653 + }
1654 +
1655 + $host = parse_url( $real_url, PHP_URL_HOST );
1656 + $ip = gethostbyname( $host );
1657 +
1658 + if ( $website != null ) {
1659 + MainWP_DB::Instance()->insertOrUpdateRequestLog( $website->id, $ip, null, microtime( true ) );
1660 + }
1661 +
1662 + $raw_response = isset( $others[ 'raw_response' ] ) && $others[ 'raw_response' ] == 'yes' ? true : false;
1663 +
1664 + MainWP_Logger::Instance()->debugForWebsite( $website, '_fetchUrl', 'http status: [' . $http_status . '] err: [' . $err . '] data: [' . $data . ']' );
1665 + if ( $http_status == '400' )
1666 + MainWP_Logger::Instance()->debugForWebsite( $website, '_fetchUrl', 'post data: [' . print_r( $postdata, 1 ) . ']' );
1667 +
1668 + if ( ( $data === false ) && ( $http_status == 0 ) ) {
1669 + MainWP_Logger::Instance()->debugForWebsite( $website, 'fetchUrl', '[' . $url . '] HTTP Error: [status=0][' . $err . ']' );
1670 + throw new MainWP_Exception( 'HTTPERROR', $err );
1671 + } else if ( empty( $data ) && !empty( $err ) ) {
1672 + MainWP_Logger::Instance()->debugForWebsite( $website, 'fetchUrl', '[' . $url . '] HTTP Error: [status=' . $http_status . '][' . $err . ']' );
1673 + throw new MainWP_Exception( 'HTTPERROR', $err );
1674 + } else if ( preg_match( '/<mainwp>(.*)<\/mainwp>/', $data, $results ) > 0 ) {
1675 + $result = $results[ 1 ];
1676 + $information = unserialize( base64_decode( $result ) );
1677 + MainWP_Logger::Instance()->debugForWebsite( $website, '_fetchUrl', 'information: [OK]' );
1678 + return $information;
1679 + } else if ( $http_status == 200 && ! empty( $err ) ) { // unexpected http error
1680 + throw new MainWP_Exception( 'HTTPERROR', $err );
1681 + } else if ( $raw_response ) {
1682 + MainWP_Logger::Instance()->debugForWebsite( $website, '_fetchUrl', 'Response: [RAW]' );
1683 + return $data;
1684 + } else {
1685 + MainWP_Logger::Instance()->debugForWebsite( $website, 'fetchUrl', '[' . $url . '] Result was: [' . $data . ']' );
1686 + throw new MainWP_Exception( 'NOMAINWP', $url );
1687 + }
1688 + }
1689 +
1690 + public static function checkPremiumUpdates( $updates, $type ) {
1691 +
1692 + if (!is_array($updates) || empty($updates)) {
1693 + return false;
1093 1694 }
1094 1695
1095 - return array(
1096 - 'val' => $val,
1097 - 'critical' => $issue_counts['critical'],
1098 - );
1099 - }
1696 + if ( $type == 'plugin' ) {
1100 1697
1698 + $premiums = array(
1699 + 'ithemes-security-pro/ithemes-security-pro.php',
1700 + 'monarch/monarch.php',
1701 + 'cornerstone/cornerstone.php',
1702 + 'updraftplus/updraftplus.php',
1703 + 'wp-all-import-pro/wp-all-import-pro.php',
1704 + 'bbq-pro/bbq-pro.php',
1705 + 'seedprod-coming-soon-pro-5/seedprod-coming-soon-pro-5.php',
1706 + 'elementor-pro/elementor-pro.php',
1707 + 'bbpowerpack/bb-powerpack.php',
1708 + 'bb-ultimate-addon/bb-ultimate-addon.php',
1709 + 'webarx/webarx.php',
1710 + 'leco-client-portal/leco-client-portal.php',
1711 + 'elementor-extras/elementor-extras.php',
1712 + 'wp-schema-pro/wp-schema-pro.php',
1713 + 'convertpro/convertpro.php',
1714 + 'astra-addon/astra-addon.php',
1715 + 'astra-portfolio/astra-portfolio.php',
1716 + 'astra-pro-sites/astra-pro-sites.php',
1717 + 'custom-facebook-feed-pro/custom-facebook-feed.php',
1718 + 'convertpro/convertpro.php',
1719 + 'convertpro-addon/convertpro-addon.php',
1720 + 'wp-schema-pro/wp-schema-pro.php',
1721 + 'ultimate-elementor/ultimate-elementor.php',
1722 + 'gp-premium/gp-premium.php'
1723 + );
1101 1724
1102 - /**
1103 - * Get HTTP code.
1104 - *
1105 - * @param int $code HTTP code.
1106 - *
1107 - * @return array $http_codes HTTP code.
1108 - */
1109 - public static function get_http_codes( $code = false ) {
1725 + $premiums = apply_filters('mainwp_detect_premiums_updates', $premiums ); // deprecated 3.5.4
1110 1726
1111 - $http_codes = array(
1112 - 100 => 'Continue',
1113 - 101 => 'Switching Protocols',
1114 - 200 => 'OK',
1115 - 201 => 'Created',
1116 - 202 => 'Accepted',
1117 - 203 => 'Non-Authoritative Information',
1118 - 204 => 'No Content',
1119 - 205 => 'Reset Content',
1120 - 206 => 'Partial Content',
1121 - 300 => 'Multiple Choices',
1122 - 301 => 'Moved Permanently',
1123 - 302 => 'Found',
1124 - 303 => 'See Other',
1125 - 304 => 'Not Modified',
1126 - 305 => 'Use Proxy',
1127 - 306 => '(Unused)',
1128 - 307 => 'Temporary Redirect',
1129 - 400 => 'Bad Request',
1130 - 401 => 'Unauthorized',
1131 - 402 => 'Payment Required',
1132 - 403 => 'Forbidden',
1133 - 404 => 'Not Found',
1134 - 405 => 'Method Not Allowed',
1135 - 406 => 'Not Acceptable',
1136 - 407 => 'Proxy Authentication Required',
1137 - 408 => 'Request Timeout',
1138 - 409 => 'Conflict',
1139 - 410 => 'Gone',
1140 - 411 => 'Length Required',
1141 - 412 => 'Precondition Failed',
1142 - 413 => 'Request Entity Too Large',
1143 - 414 => 'Request-URI Too Long',
1144 - 415 => 'Unsupported Media Type',
1145 - 416 => 'Requested Range Not Satisfiable',
1146 - 417 => 'Expectation Failed',
1147 - 500 => 'Internal Server Error',
1148 - 501 => 'Not Implemented',
1149 - 502 => 'Bad Gateway',
1150 - 503 => 'Service Unavailable',
1151 - 504 => 'Gateway Timeout',
1152 - 505 => 'HTTP Version Not Supported',
1153 - );
1727 + $premiums = apply_filters('mainwp_detect_premium_plugins_update', $premiums );
1154 1728
1155 - if ( false === $code ) {
1156 - return $http_codes;
1157 - }
1729 + if ( is_array($premiums) && count($premiums) > 0 ) {
1730 + foreach( $updates as $info ) {
1731 + if ( isset($info['slug']) ) {
1732 + if ( in_array( $info['slug'], $premiums ) ) {
1733 + return true;
1734 + } else if ( false !== strpos( $info['slug'], 'yith-') ) { // detect for Yithemes plugins
1735 + return true;
1736 + }
1737 + }
1738 + }
1739 + }
1158 1740
1159 - return isset( $http_codes[ $code ] ) ? $http_codes[ $code ] : '';
1160 - }
1741 + } else if ( $type == 'theme') {
1161 1742
1162 - /**
1163 - * Method valid_input_emails().
1164 - *
1165 - * @param string $emails Input emails string.
1166 - *
1167 - * @return string $valid_emails Valid emails string.
1168 - */
1169 - public static function valid_input_emails( $emails ) {
1743 + $premiums = array();
1170 1744
1171 - if ( is_string( $emails ) ) {
1172 - $emails = array_filter( explode( ',', $emails ) );
1173 - }
1745 + $premiums = apply_filters('mainwp_detect_premium_themes_update', $premiums );
1174 1746
1175 - $valid_emails = array();
1176 - if ( is_array( $emails ) ) {
1177 - foreach ( $emails as $email ) {
1178 - $email = esc_html( trim( $email ) );
1179 - if ( ! empty( $email ) && ! in_array( $email, $valid_emails, true ) ) {
1180 - $valid_emails[] = $email;
1747 + if ( is_array($premiums) && count($premiums) > 0 ) {
1748 + foreach( $updates as $info ) {
1749 + if ( isset($info['slug']) ) {
1750 + if ( in_array( $info['slug'], $premiums ) ) {
1751 + return true;
1752 + }
1753 + }
1181 1754 }
1182 1755 }
1756 +
1183 1757 }
1184 - $valid_emails = implode( ',', $valid_emails );
1185 - return $valid_emails;
1758 +
1759 + return false;
1186 1760 }
1187 1761
1188 - /**
1189 - * Method check_image_file_name()
1190 - *
1191 - * Check if the file image.
1192 - *
1193 - * @param string $filename Contains image (file) name.
1194 - *
1195 - * @return true|false valid name or not.
1196 - */
1197 - public static function check_image_file_name( $filename ) {
1198 - if ( validate_file( $filename ) ) {
1762 + public static function checkRequestUpdatePremium( $list, $type ) {
1763 +
1764 + $updates = explode( ",", $list );
1765 +
1766 + if ( !is_array($updates) || empty($updates) ) {
1199 1767 return false;
1200 1768 }
1201 1769
1202 - $allowed_files = array( 'jpg', 'jpeg', 'jpe', 'gif', 'png', 'bmp', 'tif', 'tiff', 'ico' );
1203 - $file_ext = array_values( array_slice( explode( '.', $filename ), -1 ) )[0];
1204 - $file_ext = strtolower( $file_ext );
1205 - if ( ! in_array( $file_ext, $allowed_files ) ) {
1770 + // limit support request one premium one site at the moment
1771 + if ( count($updates) >1 ) {
1206 1772 return false;
1207 1773 }
1208 1774
1209 - return true;
1210 - }
1775 + if ( $type == 'plugin' ) {
1211 1776
1212 - /**
1213 - * Method check_abandoned()
1214 - *
1215 - * Get site's icon.
1216 - *
1217 - * @param mixed $siteId site's id.
1218 - * @param string $which to check plugin/theme.
1219 - *
1220 - * @return array result error or success
1221 - * @throws \MainWP_Exception Error message.
1222 - */
1223 - public static function check_abandoned( $siteId = null, $which = '' ) { // phpcs:ignore -- NOSONAR - complex.
1224 - if ( static::ctype_digit( $siteId ) ) {
1225 - $website = MainWP_DB::instance()->get_website_by_id( $siteId );
1226 - if ( MainWP_System_Utility::can_edit_website( $website ) ) {
1227 - $error = '';
1228 - try {
1229 - $information = MainWP_Connect::fetch_url_authed( $website, 'check_abandoned', array( 'which' => $which ) );
1230 - if ( is_array( $information ) && isset( $information['sync'] ) && ! empty( $information['sync'] ) ) {
1231 - MainWP_Sync::sync_information_array( $website, $information['sync'] );
1232 - unset( $information['sync'] );
1777 + $update_premiums = array(
1778 + 'yith-woocommerce-request-a-quote-premium/init.php'
1779 + );
1780 +
1781 + $update_premiums = apply_filters('mainwp_request_update_premium_plugins', $update_premiums );
1782 +
1783 + if ( is_array($update_premiums) && count($update_premiums) > 0 ) {
1784 + foreach( $updates as $slug ) {
1785 + if ( !empty($slug) ) {
1786 + if ( in_array( $slug, $update_premiums ) ) {
1787 + return true;
1788 + }
1233 1789 }
1234 - } catch ( MainWP_Exception $e ) {
1235 - $error = $e->getMessage();
1236 1790 }
1791 + }
1237 1792
1238 - if ( '' !== $error ) {
1239 - return array( 'error' => $error );
1240 - } elseif ( isset( $information['success'] ) && ! empty( $information['success'] ) ) {
1241 - return array( 'result' => 'success' );
1242 - } else {
1243 - return array( 'undefined_error' => true );
1793 + } else if ( $type == 'theme' ) {
1794 +
1795 + $update_premiums = array();
1796 + $update_premiums = apply_filters('mainwp_request_update_premium_themes', $update_premiums );
1797 + if ( is_array($update_premiums) && count($update_premiums) > 0 ) {
1798 + foreach( $themes as $slug ) {
1799 + if ( !empty($slug) ) {
1800 + if ( in_array( $slug, $update_premiums ) ) {
1801 + return true;
1802 + }
1803 + }
1244 1804 }
1245 1805 }
1806 +
1246 1807 }
1247 - return array( 'result' => 'NOSITE' );
1808 + return false;
1809 +
1248 1810 }
1249 1811
1250 - /**
1251 - * Get directory or slug of plugin.
1252 - *
1253 - * @param string $slug Plugin slug.
1254 - *
1255 - * @return string $value directory or slug of plugin.
1256 - */
1257 - public static function get_dir_slug( $slug ) {
1258 - $value = '';
1259 - if ( false === strpos( $slug, '/' ) ) {
1260 - if ( false !== strpos( $slug, '.' ) ) {
1261 - $value = substr( $slug, 0, strpos( $slug, '.' ) );
1262 - }
1812 + static function redirect_request_site( $website, $where_url ) {
1813 +
1814 + $request_url = MainWP_Utility::getGetDataAuthed( $website, $where_url );
1815 +
1816 + $agent = 'Mozilla/5.0 (compatible; MainWP/' . MainWP_System::$version . '; +http://mainwp.com)';
1817 + $args = array(
1818 + 'timeout' => 25,
1819 + 'httpversion' => '1.1',
1820 + 'User-Agent' => $agent,
1821 + );
1822 +
1823 + if ( !empty($website->http_user) && !empty($website->http_pass) ) {
1824 + $args['headers'] = array(
1825 + 'Authorization' => 'Basic ' . base64_encode( $website->http_user . ':' . $website->http_pass )
1826 + );
1827 + }
1828 + return wp_remote_get( $request_url, $args );
1829 + }
1830 +
1831 + static function request_premiums_update( $website, $type, $list ) {
1832 + if ($type == 'plugin' ) {
1833 + $where_url = 'plugins.php?_request_update_premiums_type=plugin&list=' . $list;
1834 + } else if ( $type == 'theme' ) {
1835 + $where_url = 'update-core.php?_request_update_premiums_type=theme&list=' . $list;
1263 1836 } else {
1264 - $value = dirname( $slug );
1837 + return null; // need to null
1265 1838 }
1266 - if ( empty( $value ) ) {
1267 - return $slug;
1268 - }
1269 - return $value;
1839 + self::redirect_request_site( $website, $where_url );
1840 + return true;
1270 1841 }
1271 1842
1272 - /**
1273 - * Metho get_siteview_mode().
1274 - *
1275 - * Get site view mode.
1276 - *
1277 - * @return string $viewmode Site view mode.
1278 - */
1279 - public static function get_siteview_mode() {
1280 - $viewmode = get_user_option( 'mainwp_sitesviewmode' );
1281 - if ( 'grid' !== $viewmode && 'table' !== $viewmode ) {
1282 - $viewmode = 'grid';
1843 + static function try_to_detect_premiums_update( $website, $type ) {
1844 + if ($type == 'plugin' ) {
1845 + $where_url = 'plugins.php?_detect_plugins_updates=yes';
1846 + } else if ( $type == 'theme' ) {
1847 + $where_url = 'update-core.php?_detect_themes_updates=yes';
1848 + } else {
1849 + return false;
1283 1850 }
1284 - return $viewmode;
1851 + self::redirect_request_site( $website, $where_url );
1285 1852 }
1286 1853
1287 1854
1288 - /**
1289 - * Metho delete_file().
1290 - *
1291 - * Delete file.
1292 - *
1293 - * @param string $file_path File path.
1294 - *
1295 - * @return bool true|false.
1296 - */
1297 - public static function delete_file( $file_path ) {
1855 + static function ctype_digit( $str ) {
1856 + return ( is_string( $str ) || is_int( $str ) || is_float( $str ) ) && preg_match( '/^\d+\z/', $str );
1857 + }
1298 1858
1299 - global $wp_filesystem;
1859 + static function log( $text ) {
1300 1860
1301 - if ( ! empty( $file_path ) ) {
1302 - if ( $wp_filesystem ) {
1303 - if ( $wp_filesystem->exists( $file_path ) ) {
1304 - $wp_filesystem->delete( $file_path );
1305 - }
1306 - } elseif ( file_exists( $file_path ) ) {
1307 - wp_delete_file( $file_path );
1308 - }
1309 - return true;
1310 - }
1861 + }
1311 1862
1312 - return false;
1313 - }
1863 + public static function downloadToFile( $url, $file, $size = false, $http_user = null, $http_pass = null ) {
1864 + if ( @file_exists( $file ) && ( ( $size === false ) || ( @filesize( $file ) > $size ) ) ) {
1865 + @unlink( $file );
1866 + }
1314 1867
1315 - /**
1316 - * Method get_disable_functions()
1317 - *
1318 - * Get disable functions.
1319 - *
1320 - * @return string
1321 - */
1322 - public function get_disable_functions() {
1323 - if ( null === static::$disabled_functions ) {
1324 - static::$disabled_functions = ini_get( 'disable_functions' );
1325 - }
1326 - return static::$disabled_functions;
1327 - }
1868 + if ( !@file_exists( @dirname( $file ) ) ) {
1869 + @mkdir( @dirname( $file ), 0777, true );
1870 + }
1328 1871
1329 - /**
1330 - * Method is_disable_functions()
1331 - *
1332 - * Check if it is disabled functions.
1333 - *
1334 - * @param string $func Function name to check.
1335 - *
1336 - * @return string
1337 - */
1338 - public function is_disabled_functions( $func ) {
1339 - $dis_funcs = $this->get_disable_functions();
1872 + if ( !@file_exists( @dirname( $file ) ) ) {
1873 + throw new MainWP_Exception( __( 'MainWP plugin could not create directory in order to download the file.', 'mainwp' ) );
1874 + }
1340 1875
1341 - if ( ! empty( $dis_funcs ) && ( false !== stristr( $dis_funcs, $func ) ) ) {
1342 - return true;
1343 - }
1344 - return false;
1345 - }
1876 + if ( !@is_writable( @dirname( $file ) ) ) {
1877 + throw new MainWP_Exception( __( 'MainWP upload directory is not writable.', 'mainwp' ) );
1878 + }
1346 1879
1347 - /**
1348 - * Method hook_verify_ping_nonce()
1349 - *
1350 - * Verify nonce without session and user id.
1351 - *
1352 - * @param bool $input_value Boolean value, it should always be FALSE.
1353 - * @param string $nonce Nonce to verify.
1354 - * @param mixed $siteid Site ID.
1355 - *
1356 - * @return mixed If verified return 1 or 2, if not return false.
1357 - */
1358 - public static function hook_verify_ping_nonce( $input_value, $nonce = '', $siteid = false ) {
1359 - unset( $input_value );
1360 - $action = 'pingnonce';
1361 - return static::verify_site_nonce( $nonce, $action, $siteid );
1362 - }
1880 + $fp = fopen( $file, 'a' );
1881 + //$agent = 'Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)';
1882 + $agent = 'Mozilla/5.0 (compatible; MainWP/' . MainWP_System::$version . '; +http://mainwp.com)';
1883 + if ( $size !== false ) {
1884 + if ( @file_exists( $file ) ) {
1885 + $size = @filesize( $file );
1886 + $url .= '&foffset=' . $size;
1887 + }
1888 + }
1889 + $ch = curl_init( str_replace( ' ', '%20', $url ) );
1363 1890
1364 - /**
1365 - * Method create_site_nonce()
1366 - *
1367 - * Create action nonce for site.
1368 - *
1369 - * @param mixed $action Action to perform.
1370 - * @param mixed $siteid Site ID.
1371 - *
1372 - * @return string Custom nonce.
1373 - */
1374 - public static function create_site_nonce( $action = - 1, $siteid = false ) {
1375 - if ( empty( $action ) || empty( $siteid || ! is_numeric( $siteid ) ) ) {
1891 + // cURL offers really easy proxy support.
1892 + $proxy = new WP_HTTP_Proxy();
1893 + if ( $proxy->is_enabled() && $proxy->send_through_proxy( $url ) ) {
1894 + curl_setopt( $ch, CURLOPT_PROXYTYPE, CURLPROXY_HTTP );
1895 + curl_setopt( $ch, CURLOPT_PROXY, $proxy->host() );
1896 + curl_setopt( $ch, CURLOPT_PROXYPORT, $proxy->port() );
1897 +
1898 + if ( $proxy->use_authentication() ) {
1899 + curl_setopt( $ch, CURLOPT_PROXYAUTH, CURLAUTH_ANY );
1900 + curl_setopt( $ch, CURLOPT_PROXYUSERPWD, $proxy->authentication() );
1901 + }
1902 + }
1903 +
1904 + curl_setopt( $ch, CURLOPT_FILE, $fp );
1905 + curl_setopt( $ch, CURLOPT_USERAGENT, $agent );
1906 + @curl_setopt( $ch, CURLOPT_ENCODING, 'none'); // to fix
1907 + curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, true );
1908 + if ( !empty( $http_user ) && !empty( $http_pass ) ) {
1909 + $http_pass = stripslashes($http_pass); // to fix
1910 + curl_setopt( $ch, CURLOPT_USERPWD, "$http_user:$http_pass" );
1911 + }
1912 + curl_exec( $ch );
1913 + curl_close( $ch );
1914 + fclose( $fp );
1915 + }
1916 +
1917 + static function uploadImage( $img_url, $img_data = array() ) {
1918 + if ( !is_array( $img_data ) )
1919 + $img_data = array();
1920 + include_once( ABSPATH . 'wp-admin/includes/file.php' ); //Contains download_url
1921 + $upload_dir = wp_upload_dir();
1922 + //Download $img_url
1923 + $temporary_file = download_url( $img_url );
1924 +
1925 + if ( is_wp_error( $temporary_file ) ) {
1926 + throw new Exception( 'Error: ' . $temporary_file->get_error_message() );
1927 + } else {
1928 + $upload_dir = wp_upload_dir();
1929 + $local_img_path = $upload_dir[ 'path' ] . DIRECTORY_SEPARATOR . basename( $img_url ); //Local name
1930 + $local_img_url = $upload_dir[ 'url' ] . '/' . basename( $img_url );
1931 + $moved = @rename( $temporary_file, $local_img_path );
1932 + if ( $moved ) {
1933 + $wp_filetype = wp_check_filetype( basename( $img_url ), null ); //Get the filetype to set the mimetype
1934 + $attachment = array(
1935 + 'post_mime_type' => $wp_filetype[ 'type' ],
1936 + 'post_title' => isset( $img_data[ 'title' ] ) && !empty( $img_data[ 'title' ] ) ? $img_data[ 'title' ] : preg_replace( '/\.[^.]+$/', '', basename( $img_url ) ),
1937 + 'post_content' => isset( $img_data[ 'description' ] ) && !empty( $img_data[ 'description' ] ) ? $img_data[ 'description' ] : '',
1938 + 'post_excerpt' => isset( $img_data[ 'caption' ] ) && !empty( $img_data[ 'caption' ] ) ? $img_data[ 'caption' ] : '',
1939 + 'post_status' => 'inherit',
1940 + );
1941 + $attach_id = wp_insert_attachment( $attachment, $local_img_path ); //Insert the image in the database
1942 + require_once( ABSPATH . 'wp-admin/includes/image.php' );
1943 + $attach_data = wp_generate_attachment_metadata( $attach_id, $local_img_path );
1944 + wp_update_attachment_metadata( $attach_id, $attach_data ); //Update generated metadata
1945 + if ( isset( $img_data[ 'alt' ] ) && !empty( $img_data[ 'alt' ] ) )
1946 + update_post_meta( $attach_id, '_wp_attachment_image_alt', $img_data[ 'alt' ] );
1947 + return array( 'id' => $attach_id, 'url' => $local_img_url );
1948 + }
1949 + }
1950 + if ( file_exists( $temporary_file ) ) {
1951 + unlink( $temporary_file );
1952 + }
1953 +
1954 + return null;
1955 + }
1956 +
1957 + static function getBaseDir() {
1958 + $upload_dir = wp_upload_dir();
1959 +
1960 + return $upload_dir[ 'basedir' ] . DIRECTORY_SEPARATOR;
1961 + }
1962 +
1963 + public static function getIconsDir() {
1964 + $dirs = self::getMainWPDir();
1965 + $dir = $dirs[ 0 ] . 'icons' . DIRECTORY_SEPARATOR;
1966 + $url = $dirs[ 1 ] . 'icons/';
1967 + if ( !file_exists( $dir ) ) {
1968 + @mkdir( $dir, 0777, true );
1969 + }
1970 + if ( !file_exists( $dir . 'index.php' ) ) {
1971 + @touch( $dir . 'index.php' );
1972 + }
1973 + return array( $dir, $url );
1974 + }
1975 +
1976 + public static function getMainWPDir() {
1977 + $upload_dir = wp_upload_dir();
1978 + $dir = $upload_dir[ 'basedir' ] . DIRECTORY_SEPARATOR . 'mainwp' . DIRECTORY_SEPARATOR;
1979 + $url = $upload_dir[ 'baseurl' ] . '/mainwp/';
1980 + if ( !file_exists( $dir ) ) {
1981 + @mkdir( $dir, 0777, true );
1982 + }
1983 + if ( !file_exists( $dir . 'index.php' ) ) {
1984 + @touch( $dir . 'index.php' );
1985 + }
1986 +
1987 + return array( $dir, $url );
1988 + }
1989 +
1990 + public static function getDownloadUrl( $what, $filename ) {
1991 + $specificDir = MainWP_Utility::getMainWPSpecificDir( $what );
1992 + $mwpDir = MainWP_Utility::getMainWPDir();
1993 + $mwpDir = $mwpDir[ 0 ];
1994 + $fullFile = $specificDir . $filename;
1995 +
1996 + return admin_url( '?sig=' . md5( filesize( $fullFile ) ) . '&mwpdl=' . rawurlencode( str_replace( $mwpDir, '', $fullFile ) ) );
1997 + }
1998 +
1999 + public static function getMainWPSpecificDir( $dir = null ) {
2000 + if ( MainWP_System::Instance()->isSingleUser() ) {
2001 + $userid = 0;
2002 + } else {
2003 + global $current_user;
2004 + $userid = $current_user->ID;
2005 + }
2006 +
2007 + $dirs = self::getMainWPDir();
2008 + $newdir = $dirs[ 0 ] . $userid . ( $dir != null ? DIRECTORY_SEPARATOR . $dir . DIRECTORY_SEPARATOR : '' );
2009 +
2010 + if ( !file_exists( $newdir ) ) {
2011 + @mkdir( $newdir, 0777, true );
2012 + }
2013 +
2014 + if ( $dirs[ 0 ] . $userid != null && !file_exists( trailingslashit( $dirs[ 0 ] . $userid ) . '.htaccess' ) ) {
2015 + $file = @fopen( trailingslashit( $dirs[ 0 ] . $userid ) . '.htaccess', 'w+' );
2016 + @fwrite( $file, 'deny from all' );
2017 + @fclose( $file );
2018 + }
2019 +
2020 + return $newdir;
2021 + }
2022 +
2023 + public static function getMainWPSpecificUrl( $dir ) {
2024 + if ( MainWP_System::Instance()->isSingleUser() ) {
2025 + $userid = 0;
2026 + } else {
2027 + global $current_user;
2028 + $userid = $current_user->ID;
2029 + }
2030 + $dirs = self::getMainWPDir();
2031 +
2032 + return $dirs[ 1 ] . $userid . '/' . $dir . '/';
2033 + }
2034 +
2035 + public static function getAlexaRank( $domain ) {
2036 + $remote_url = 'http://data.alexa.com/data?cli=10&dat=snbamz&url=' . trim( $domain );
2037 + $search_for = '<POPULARITY URL';
2038 + $part = '';
2039 + if ( $handle = @fopen( $remote_url, 'r' ) ) {
2040 + while ( !feof( $handle ) ) {
2041 + $part .= fread( $handle, 100 );
2042 + $pos = strpos( $part, $search_for );
2043 + if ( $pos === false ) {
2044 + continue;
2045 + } else {
2046 + break;
2047 + }
2048 + }
2049 + $part .= fread( $handle, 100 );
2050 + fclose( $handle );
2051 + }
2052 + if ( !stristr( $part, '<ALEXA' ) )
2053 + return NULL;
2054 + if ( !stristr( $part, $search_for ) ) {
2055 + return 0;
2056 + }
2057 +
2058 + $str = explode( $search_for, $part );
2059 + $str = explode( '"/>', $str[ 1 ] );
2060 + $str = array_shift( $str );
2061 + $str = explode( 'TEXT="', $str );
2062 +
2063 + return $str[ 1 ];
2064 + }
2065 +
2066 + protected static function StrToNum( $Str, $Check, $Magic ) {
2067 + $Int32Unit = 4294967296; // 2^32
2068 +
2069 + $length = strlen( $Str );
2070 + for ( $i = 0; $i < $length; $i ++ ) {
2071 + $Check *= $Magic;
2072 + //If the float is beyond the boundaries of integer (usually +/- 2.15e+9 = 2^31),
2073 + // the result of converting to integer is undefined
2074 + // refer to http://www.php.net/manual/en/language.types.integer.php
2075 + if ( $Check >= $Int32Unit ) {
2076 + $Check = ( $Check - $Int32Unit * (int) ( $Check / $Int32Unit ) );
2077 + //if the check less than -2^31
2078 + $Check = ( $Check < - 2147483648 ) ? ( $Check + $Int32Unit ) : $Check;
2079 + }
2080 + $Check += ord( $Str{$i} );
2081 + }
2082 +
2083 + return $Check;
2084 + }
2085 +
2086 + //--> for google pagerank
2087 + /*
2088 + * Genearate a hash for a url
2089 + */
2090 + protected static function HashURL( $String ) {
2091 + $Check1 = MainWP_Utility::StrToNum( $String, 0x1505, 0x21 );
2092 + $Check2 = MainWP_Utility::StrToNum( $String, 0, 0x1003F );
2093 +
2094 + $Check1 >>= 2;
2095 + $Check1 = ( ( $Check1 >> 4 ) & 0x3FFFFC0 ) | ( $Check1 & 0x3F );
2096 + $Check1 = ( ( $Check1 >> 4 ) & 0x3FFC00 ) | ( $Check1 & 0x3FF );
2097 + $Check1 = ( ( $Check1 >> 4 ) & 0x3C000 ) | ( $Check1 & 0x3FFF );
2098 +
2099 + $T1 = ( ( ( ( $Check1 & 0x3C0 ) << 4 ) | ( $Check1 & 0x3C ) ) << 2 ) | ( $Check2 & 0xF0F );
2100 + $T2 = ( ( ( ( $Check1 & 0xFFFFC000 ) << 4 ) | ( $Check1 & 0x3C00 ) ) << 0xA ) | ( $Check2 & 0xF0F0000 );
2101 +
2102 + return ( $T1 | $T2 );
2103 + }
2104 +
2105 + //--> for google pagerank
2106 + /*
2107 + * genearate a checksum for the hash string
2108 + */
2109 + protected static function CheckHash( $Hashnum ) {
2110 + $CheckByte = 0;
2111 + $Flag = 0;
2112 +
2113 + $HashStr = sprintf( '%u', $Hashnum );
2114 + $length = strlen( $HashStr );
2115 +
2116 + for ( $i = $length - 1; $i >= 0; $i -- ) {
2117 + $Re = $HashStr{$i};
2118 + if ( 1 === ( $Flag % 2 ) ) {
2119 + $Re += $Re;
2120 + $Re = (int) ( $Re / 10 ) + ( $Re % 10 );
2121 + }
2122 + $CheckByte += $Re;
2123 + $Flag ++;
2124 + }
2125 +
2126 + $CheckByte %= 10;
2127 + if ( 0 !== $CheckByte ) {
2128 + $CheckByte = 10 - $CheckByte;
2129 + if ( 1 === ( $Flag % 2 ) ) {
2130 + if ( 1 === ( $CheckByte % 2 ) ) {
2131 + $CheckByte += 9;
2132 + }
2133 + $CheckByte >>= 1;
2134 + }
2135 + }
2136 +
2137 + return '7' . $CheckByte . $HashStr;
2138 + }
2139 +
2140 + //get google pagerank
2141 + public static function getpagerank( $url ) {
2142 + $query = 'http://toolbarqueries.google.com/tbr?client=navclient-auto&ch=' . MainWP_Utility::CheckHash( MainWP_Utility::HashURL( $url ) ) . '&features=Rank&q=info:' . $url . '&num=100&filter=0';
2143 + $data = MainWP_Utility::file_get_contents_curl( $query );
2144 + $pos = strpos( $data, 'Rank_' );
2145 + if ( $pos === false ) {
2146 + return false;
2147 + } else {
2148 + $pagerank = substr( $data, $pos + 9 );
2149 +
2150 + return $pagerank;
2151 + }
2152 + }
2153 +
2154 + public static function get_file_content( $url ) {
2155 + $data = self::file_get_contents_curl( $url );
2156 + if ( empty( $data ) )
2157 + return false;
2158 + return $data;
2159 + }
2160 +
2161 + protected static function file_get_contents_curl( $url ) {
2162 + //$agent = 'Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)';
2163 + $agent = 'Mozilla/5.0 (compatible; MainWP/' . MainWP_System::$version . '; +http://mainwp.com)';
2164 + $ch = curl_init();
2165 +
2166 + // cURL offers really easy proxy support.
2167 + $proxy = new WP_HTTP_Proxy();
2168 + if ( $proxy->is_enabled() && $proxy->send_through_proxy( $url ) ) {
2169 + curl_setopt( $ch, CURLOPT_PROXYTYPE, CURLPROXY_HTTP );
2170 + curl_setopt( $ch, CURLOPT_PROXY, $proxy->host() );
2171 + curl_setopt( $ch, CURLOPT_PROXYPORT, $proxy->port() );
2172 +
2173 + if ( $proxy->use_authentication() ) {
2174 + curl_setopt( $ch, CURLOPT_PROXYAUTH, CURLAUTH_ANY );
2175 + curl_setopt( $ch, CURLOPT_PROXYUSERPWD, $proxy->authentication() );
2176 + }
2177 + }
2178 +
2179 + curl_setopt( $ch, CURLOPT_HEADER, 0 );
2180 + curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 ); //Set curl to return the data instead of printing it to the browser.
2181 + curl_setopt( $ch, CURLOPT_URL, $url );
2182 + curl_setopt( $ch, CURLOPT_USERAGENT, $agent );
2183 + @curl_setopt( $ch, CURLOPT_ENCODING, 'none'); // to fix
2184 +
2185 + $data = @curl_exec( $ch );
2186 + $httpCode = @curl_getinfo($ch, CURLINFO_HTTP_CODE);
2187 +
2188 + curl_close( $ch );
2189 +
2190 + if ($httpCode == 200) {
2191 + return $data;
2192 + } else {
1376 2193 return false;
1377 2194 }
1378 - return substr( wp_hash( 'site|' . $siteid . '|' . $action, 'nonce' ), - 12, 10 );
1379 - }
2195 + }
1380 2196
1381 - /**
1382 - * Method verify_site_nonce()
1383 - *
1384 - * Verify nonce without session and user id.
1385 - *
1386 - * @param string $nonce Nonce to verify.
1387 - * @param mixed $action Action to perform.
1388 - * @param mixed $siteid Site ID.
1389 - *
1390 - * @return mixed If verified return 1 or 2, if not return false.
1391 - */
1392 - public static function verify_site_nonce( $nonce, $action = - 1, $siteid = 0 ) {
1393 - $nonce = (string) $nonce;
1394 - if ( empty( $nonce ) || empty( $siteid || ! is_numeric( $siteid ) ) ) {
1395 - return false;
1396 - }
2197 + public static function getGoogleCount( $domain ) {
2198 + $content = file_get_contents( 'https://ajax.googleapis.com/ajax/services/' .
2199 + 'search/web?v=1.0&filter=0&q=site:' . urlencode( $domain ) );
2200 + $data = json_decode( $content );
1397 2201
1398 - $expected = substr( wp_hash( 'site|' . $siteid . '|' . $action, 'nonce' ), - 12, 10 );
1399 - if ( hash_equals( $expected, $nonce ) ) {
1400 - return 1;
1401 - }
1402 - return false;
1403 - }
2202 + if ( empty( $data ) ) {
2203 + return NULL;
2204 + }
2205 + if ( !property_exists( $data, 'responseData' ) ) {
2206 + return NULL;
2207 + }
2208 + if ( !is_object( $data->responseData ) || !property_exists( $data->responseData, 'cursor' ) ) {
2209 + return 0;
2210 + }
2211 + if ( !is_object( $data->responseData->cursor ) || !property_exists( $data->responseData->cursor, 'estimatedResultCount' ) ) {
2212 + return 0;
2213 + }
1404 2214
2215 + return intval( $data->responseData->cursor->estimatedResultCount );
2216 + }
1405 2217
1406 - /**
1407 - * Find for multi keywords.
1408 - *
1409 - * @param string $name_str string find on.
1410 - * @param array $words Array string input.
1411 - * @return bool True|False.
1412 - */
1413 - public static function multi_find_keywords( $name_str, $words = array() ) {
1414 - if ( ! is_array( $words ) ) {
1415 - return false;
1416 - }
1417 - foreach ( $words as $word ) {
1418 - if ( stristr( $name_str, $word ) ) {
1419 - return true;
2218 + public static function countRecursive( $array, $levels ) {
2219 + if ( $levels == 0 ) {
2220 + return count( $array );
2221 + }
2222 + $levels --;
1420 2223
1421 - }
1422 - }
1423 - return false;
1424 - }
2224 + $count = 0;
2225 + foreach ( $array as $value ) {
2226 + if ( is_array( $value ) && ( $levels > 0 ) ) {
2227 + $count += MainWP_Utility::countRecursive( $value, $levels - 1 );
2228 + } else {
2229 + $count += count( $value );
2230 + }
2231 + }
1425 2232
1426 - /**
1427 - * Merge values from right array to left array.
1428 - *
1429 - * @param array $left_array left array.
1430 - * @param array $right_array right array.
1431 - *
1432 - * @return array $result result array.
1433 - */
1434 - public static function right_array_merge( $left_array, $right_array ) {
1435 - if ( ! is_array( $left_array ) || ! is_array( $right_array ) ) {
1436 - return array();
1437 - }
1438 - $result = array_intersect_key( $right_array, $left_array );
1439 - return array_merge( $left_array, $result );
1440 - }
2233 + return $count;
2234 + }
1441 2235
2236 + public static function sortmulti( $array, $index, $order, $natsort = false, $case_sensitive = false ) {
2237 + $sorted = array();
2238 + if ( is_array( $array ) && count( $array ) > 0 ) {
2239 + foreach ( array_keys( $array ) as $key ) {
2240 + $temp[ $key ] = $array[ $key ][ $index ];
2241 + }
2242 + if ( !$natsort ) {
2243 + if ( $order == 'asc' ) {
2244 + asort( $temp );
2245 + } else {
2246 + arsort( $temp );
2247 + }
2248 + } else {
2249 + if ( $case_sensitive === true ) {
2250 + natsort( $temp );
2251 + } else {
2252 + natcasesort( $temp );
2253 + }
2254 + if ( $order != 'asc' ) {
2255 + $temp = array_reverse( $temp, true );
2256 + }
2257 + }
2258 + foreach ( array_keys( $temp ) as $key ) {
2259 + if ( is_numeric( $key ) ) {
2260 + $sorted[] = $array[ $key ];
2261 + } else {
2262 + $sorted[ $key ] = $array[ $key ];
2263 + }
2264 + }
1442 2265
1443 - /**
1444 - * Method get_set_deactivated_licenses_alerted().
1445 - *
1446 - * @param string $slug Extension slug.
1447 - * @param bool $time_value Time value.
1448 - * @param string $act get/set value.
1449 - *
1450 - * @return array $result result array.
1451 - */
1452 - public function get_set_deactivated_licenses_alerted( $slug, $time_value = false, $act = 'get' ) {
1453 - if ( null === $this->last_deactivated_alerts ) {
1454 - $this->last_deactivated_alerts = get_option( 'mainwp_cron_licenses_deactivated_alerted', array() );
1455 - if ( ! is_array( $this->last_deactivated_alerts ) ) {
1456 - $this->last_deactivated_alerts = array();
1457 - }
2266 + return $sorted;
2267 + }
2268 +
2269 + return $sorted;
2270 + }
2271 +
2272 + public static function getSubArrayHaving( $array, $index, $value ) {
2273 + $output = array();
2274 + if ( is_array( $array ) && count( $array ) > 0 ) {
2275 + foreach ( $array as $arrvalue ) {
2276 + if ( $arrvalue[ $index ] == $value ) {
2277 + $output[] = $arrvalue;
2278 + }
2279 + }
2280 + }
2281 +
2282 + return $output;
2283 + }
2284 +
2285 + public static function http_post( $request, $http_host, $path, $port = 80, $pApplication = 'main',
2286 + $throwException = false ) {
2287 +
2288 + $connect_timeout = get_option( 'mainwp_versioncontrol_timeout' );
2289 + if ( $connect_timeout !== false && ( time() - $connect_timeout ) < 60 * 60 * 12 ) { //12 hrs..
2290 + return false;
2291 + }
2292 +
2293 + if ( $pApplication == 'main' ) {
2294 + $pApplication = 'MainWP/1.1';
2295 + } //.MainWP_System::Instance()->getVersion();
2296 + else {
2297 + $pApplication = 'MainWPExtension/' . $pApplication . '/v';
2298 + }
2299 +
2300 + // use the WP HTTP class if it is available
2301 +
2302 + $http_args = array(
2303 + 'body' => $request,
2304 + 'headers' => array(
2305 + 'Content-Type' => 'application/x-www-form-urlencoded; ' .
2306 + 'charset=' . get_option( 'blog_charset' ),
2307 + 'Host' => $http_host,
2308 + 'User-Agent' => $pApplication,
2309 + ),
2310 + 'httpversion' => '1.0',
2311 + 'timeout' => 15,
2312 + );
2313 + $mainwp_url = "http://{$http_host}{$path}";
2314 +
2315 + $response = wp_remote_post( $mainwp_url, $http_args );
2316 +
2317 + if ( empty( $response ) || is_wp_error( $response ) ) {
2318 + MainWP_Utility::update_option( 'mainwp_versioncontrol_timeout', time() );
2319 + } else if ( $connect_timeout !== false ) {
2320 + delete_option( 'mainwp_versioncontrol_timeout' );
2321 + }
2322 +
2323 + if ( is_wp_error( $response ) ) {
2324 + if ( $throwException ) {
2325 + throw new Exception( $response->get_error_message() );
2326 + }
2327 +
2328 + return '';
2329 + }
2330 +
2331 + return array( $response[ 'headers' ], $response[ 'body' ] );
2332 + }
2333 +
2334 + static function trimSlashes( $elem ) {
2335 + return trim( $elem, '/' );
2336 + }
2337 +
2338 + public static function renderToolTip( $pText, $pUrl = null, $pImage = 'assests/images/info.png', $style = null ) {
2339 + $output = '<span class="tooltipcontainer">';
2340 + if ( $pUrl != null ) {
2341 + $output .= '<a href="' . esc_url($pUrl) . '" target="_blank">';
2342 + }
2343 + $output .= '<span style="color: #0074a2; font-size: 14px;" class="tooltip"><i class="question circle icon"></i></span>';
2344 + if ( $pUrl != null ) {
2345 + $output .= '</a>';
2346 + }
2347 + $output .= '<span class="tooltipcontent" style="display: none;">' . esc_html($pText);
2348 + if ( $pUrl != null ) {
2349 + $output .= ' (Click to read more)';
2350 + }
2351 + $output .= '</span></span>';
2352 + echo $output;
2353 + }
2354 +
2355 + public static function renderNoteTooltip( $pText, $pImage = '<i class="edit outline icon"></i>' ) {
2356 + $output = '<span class="tooltipcontainer">';
2357 + $output .= '<span style="font-size: 14px;" class="tooltip">' . $pImage . '</span>';
2358 + $output .= '<span class="tooltipcontent" style="display: none;">' . $pText;
2359 + $output .= '</span></span>';
2360 + return $output;
2361 + }
2362 +
2363 + public static function encrypt( $str, $pass ) {
2364 + $pass = str_split( str_pad( '', strlen( $str ), $pass, STR_PAD_RIGHT ) );
2365 + $stra = str_split( $str );
2366 + foreach ( $stra as $k => $v ) {
2367 + $tmp = ord( $v ) + ord( $pass[ $k ] );
2368 + $stra[ $k ] = chr( $tmp > 255 ? ( $tmp - 256 ) : $tmp );
2369 + }
2370 +
2371 + return base64_encode( join( '', $stra ) );
2372 + }
2373 +
2374 + public static function decrypt( $str, $pass ) {
2375 + $str = base64_decode( $str );
2376 + $pass = str_split( str_pad( '', strlen( $str ), $pass, STR_PAD_RIGHT ) );
2377 + $stra = str_split( $str );
2378 + foreach ( $stra as $k => $v ) {
2379 + $tmp = ord( $v ) - ord( $pass[ $k ] );
2380 + $stra[ $k ] = chr( $tmp < 0 ? ( $tmp + 256 ) : $tmp );
2381 + }
2382 +
2383 + return join( '', $stra );
2384 + }
2385 +
2386 + /**
2387 + * @return WP_Filesystem_Base
2388 + */
2389 + public static function getWPFilesystem() {
2390 + /** @global WP_Filesystem_Base $wp_filesystem */
2391 + global $wp_filesystem;
2392 +
2393 + if ( empty( $wp_filesystem ) ) {
2394 + ob_start();
2395 + if ( file_exists( ABSPATH . '/wp-admin/includes/screen.php' ) ) {
2396 + include_once( ABSPATH . '/wp-admin/includes/screen.php' );
2397 + }
2398 + if ( file_exists( ABSPATH . '/wp-admin/includes/template.php' ) ) {
2399 + include_once( ABSPATH . '/wp-admin/includes/template.php' );
2400 + }
2401 + $creds = request_filesystem_credentials( 'test' );
2402 + ob_end_clean();
2403 + if ( empty( $creds ) ) {
2404 + define( 'FS_METHOD', 'direct' );
2405 + }
2406 + $init = WP_Filesystem( $creds );
2407 + } else {
2408 + $init = true;
2409 + }
2410 +
2411 + return $init;
2412 + }
2413 +
2414 + public static function sanitize( $str ) {
2415 + return preg_replace( '/[\\\\\/\:"\*\?\<\>\|]+/', '', $str );
2416 + }
2417 +
2418 + public static function formatEmail( $to, $body, $title = '', $text_format = false ) {
2419 + $current_year = date( "Y" );
2420 + if ($text_format) {
2421 + $mail_send['header'] = '';
2422 +
2423 + $mail_send['body'] = $title . "\r\n" . "\r\n" .
2424 + $body . "\r\n" . "\r\n";
2425 + $mail_send['footer'] = "MainWP: https://mainwp.com" . "\r\n" .
2426 + "Extensions: https://mainwp.com/mainwp-extensions/" . "\r\n" .
2427 + "Documentation: https://mainwp.com/help/" . "\r\n" .
2428 + "Blog: https://mainwp.com/mainwp-blog/" . "\r\n" .
2429 + "Codex: https://mainwp.com/codex/" . "\r\n" .
2430 + "Support: https://mainwp.com/support/" . "\r\n" . "\r\n" .
2431 + "Follow us on Twitter: https://twitter.com/mymainwp" . "\r\n" .
2432 + "Friend us on Facebook: https://www.facebook.com/mainwp" . "\r\n" . "\r\n" .
2433 + "Copyright {$current_year} MainWP, All rights reserved.";
1458 2434 }
1459 - if ( 'get' === $act ) {
1460 - return isset( $this->last_deactivated_alerts[ $slug ] ) ? $this->last_deactivated_alerts[ $slug ] : 0;
1461 - } elseif ( 'set' === $act ) {
1462 - $this->last_deactivated_alerts[ $slug ] = intval( $time_value );
1463 - get_option( 'mainwp_cron_licenses_deactivated_alerted', $this->last_deactivated_alerts );
2435 + else
2436 + {
2437 + $mail_send[ 'header' ] = <<<EOT
2438 + <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
2439 +<html>
2440 + <head>
2441 + <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
2442 + <title> {$title} </title>
2443 + <style type="text/css">
2444 + outlook a{padding:0;}
2445 + body{width:100% !important;}
2446 + .ReadMsgBody{width:100%;}
2447 + .ExternalClass{width:100%;}
2448 + body{-webkit-text-size-adjust:none;}
2449 + body{margin:0;padding:0;}
2450 + img{
2451 + border:0;
2452 + height:auto;
2453 + line-height:100%;
2454 + outline:none;
2455 + text-decoration:none;
1464 2456 }
1465 - }
2457 + table td{
2458 + border-collapse:collapse;
2459 + }
2460 + #backgroundTable{
2461 + height:100% !important;
2462 + margin:0;
2463 + padding:0;
2464 + width:100% !important;
2465 + }
2466 + body,#backgroundTable{
2467 + background-color:#FAFAFA;
2468 + }
2469 + #templateContainer{
2470 + border:1px solid #DDDDDD;
2471 + }
2472 + h1,.h1{
2473 + color:#202020;
2474 + display:block;
2475 + font-family:Arial;
2476 + font-size:34px;
2477 + font-weight:bold;
2478 + line-height:100%;
2479 + margin-top:0;
2480 + margin-right:0;
2481 + margin-bottom:10px;
2482 + margin-left:0;
2483 + text-align:left;
2484 + }
2485 + h2,.h2{
2486 + color:#202020;
2487 + display:block;
2488 + font-family:Arial;
2489 + font-size:30px;
2490 + font-weight:bold;
2491 + line-height:100%;
2492 + margin-top:0;
2493 + margin-right:0;
2494 + margin-bottom:10px;
2495 + margin-left:0;
2496 + text-align:left;
2497 + }
2498 + h3,.h3{
2499 + color:#202020;
2500 + display:block;
2501 + font-family:Arial;
2502 + font-size:26px;
2503 + font-weight:bold;
2504 + line-height:100%;
2505 + margin-top:0;
2506 + margin-right:0;
2507 + margin-bottom:10px;
2508 + margin-left:0;
2509 + text-align:left;
2510 + }
2511 + h4,.h4{
2512 + color:#202020;
2513 + display:block;
2514 + font-family:Arial;
2515 + font-size:22px;
2516 + font-weight:bold;
2517 + line-height:100%;
2518 + margin-top:0;
2519 + margin-right:0;
2520 + margin-bottom:10px;
2521 + margin-left:0;
2522 + text-align:left;
2523 + }
2524 + #templatePreheader{
2525 + background-color:#FAFAFA;
2526 + }
2527 + .preheaderContent div{
2528 + color:#505050;
2529 + font-family:Arial;
2530 + font-size:10px;
2531 + line-height:100%;
2532 + text-align:left;
2533 + }
2534 + .preheaderContent div a:link,.preheaderContent div a:visited,.prehead=
2535 + erContent div a .yshortcuts {
2536 + color:#446200;
2537 + font-weight:normal;
2538 + text-decoration:underline;
2539 + }
2540 + #templateHeader{
2541 + background-color:#FFFFFF;
2542 + border-bottom:0;
2543 + }
2544 + .headerContent{
2545 + color:#202020;
2546 + font-family:Arial;
2547 + font-size:34px;
2548 + font-weight:bold;
2549 + line-height:100%;
2550 + padding:0;
2551 + text-align:center;
2552 + vertical-align:middle;
2553 + }
2554 + .headerContent a:link,.headerContent a:visited,.headerContent a .ysho=
2555 + rtcuts {
2556 + color:#446200;
2557 + font-weight:normal;
2558 + text-decoration:underline;
2559 + }
2560 + #headerImage{
2561 + height:auto;
2562 + max-width:600px !important;
2563 + }
2564 + #templateContainer,.bodyContent{
2565 + background-color:#FFFFFF;
2566 + }
2567 + .bodyContent div{
2568 + color:#505050;
2569 + font-family:Arial;
2570 + font-size:14px;
2571 + line-height:150%;
2572 + text-align:left;
2573 + }
2574 + .bodyContent div a:link,.bodyContent div a:visited,.bodyContent div a=
2575 + .yshortcuts {
2576 + color:#446200;
2577 + font-weight:bold;
2578 + text-decoration:underline;
2579 + }
2580 + .bodyContent img{
2581 + display:inline;
2582 + height:auto;
2583 + }
2584 + #templateFooter{
2585 + background-color:#1d1b1c;
2586 + border-top:4px solid #7fb100;
2587 + }
2588 + .footerContent div{
2589 + color:#b8b8b8;
2590 + font-family:Arial;
2591 + font-size:12px;
2592 + line-height:125%;
2593 + text-align:center;
2594 + }
2595 + .footerContent div a:link,.footerContent div a:visited,.footerContent=
2596 + div a .yshortcuts {
2597 + color:#336699;
2598 + font-weight:normal;
2599 + text-decoration:underline;
2600 + }
2601 + .footerContent img{
2602 + display:inline;
2603 + }
2604 + #social{
2605 + background-color:#1d1b1c;
2606 + border:0;
2607 + }
2608 + #social div{
2609 + text-align:center;
2610 + }
2611 + #utility{
2612 + background-color:#1d1b1c;
2613 + border:0;
2614 + }
2615 + #utility div{
2616 + text-align:center;
2617 + }
2618 + #monkeyRewards img{
2619 + max-width:190px;
2620 + }
2621 + </style>
2622 + </head>
2623 + <body leftmargin="0" marginwidth="0" topmargin="0" marginheight="0" offset="0" style="-webkit-text-size-adjust: none;margin: 0;padding: 0;background-color: #FAFAFA;width: 100% !important;">
2624 + <center>
2625 + <table border="0" cellpadding="0" cellspacing="0" height="100%" width="100%" id="backgroundTable" style="margin: 0;padding:0;background-color: #FAFAFA;height: 100% !important;width: 100% !important;">
2626 + <tr>
2627 + <td align="center" valign="top" style="border-collapse: collapse;">
1466 2628
1467 - /**
1468 - * Method get_remote_favicon().
1469 - *
1470 - * @param string $url Url.
1471 - * @param string $favi favicon file name.
1472 - * @param int $item_id item id.
1473 - * @param string $file_prefix favicon file prefix name.
1474 - *
1475 - * @return mixed result.
1476 - */
1477 - public static function get_remote_favicon( $url, $favi = '', $item_id = false, $file_prefix = '' ) { // phpcs:ignore -- NOSONAR - complex.
2629 + <!-- // Begin: Template Pre-header \\ -->
1478 2630
1479 - if ( empty( $favi ) ) {
1480 - $favi = 'favicon.ico';
2631 + <table border="0" cellpadding="10" cellspacing="0" width="600" id="templatePreheader" style="background-color: #FAFAFA;">
2632 + <tr>
2633 + <td valign="top" class="preheaderContent" style="border-collapse: collapse;">
2634 +
2635 + <!-- // Begin: Standard Preheader \ -->
2636 +
2637 + <table border="0" cellpadding="10" cellspacing="0" width="100%">
2638 + <tr>
2639 + <td valign="top" style="border-collapse: collapse;">
2640 + <div style="color: #505050;font-family: Arial;font-size: 10px;line-height: 100%;text-align: left;"></div>
2641 + </td>
2642 + <td valign="top" width="190" style="border-collapse: collapse;">
2643 + <div style="color: #505050;font-family: Arial;font-size: 10px;line-height: 100%;text-align: left;"></div>
2644 + </td>
2645 + </tr>
2646 + </table>
2647 +
2648 + <!-- // End: Standard Preheader \ -->
2649 +
2650 + </td>
2651 + </tr>
2652 + </table>
2653 +
2654 + <!-- // End: Template Preheader \\ -->
2655 +
2656 + <table border="0" cellpadding="0" cellspacing="0" width="600" id="templateContainer" style="border: 1px solid #DDDDDD;background-color: #FFFFFF;">
2657 + <tr>
2658 + <td align="center" valign="top" style="border-collapse: collapse;">
2659 +
2660 + <!-- // Begin: Template Header \\ -->
2661 +
2662 + <table border="0" cellpadding="0" cellspacing="0" width="600" id="templateHeader" style="background-color: #FFFFFF;border-bottom: 0;">
2663 + <tr>
2664 + <td class="headerContent" style="border-collapse: collapse;color: #202020;font-family: Arial;font-size: 34px;font-weight: bold;line-height: 100%;padding: 0;text-align: center;vertical-align: middle;">
2665 +
2666 + <!-- // Begin: Standard Header Image \\ -->
2667 +
2668 + <a href="https://mainwp.com" target="_blank" style="color: #446200;font-weight: normal;text-decoration: underline;"><img src="https://gallery.mailchimp.com/f3ac05fd307648a9c6bbe320a/images/header.png" alt="MainWP" border="0" style="border: px none;border-color: ;border-style: none;border-width: px;height: 130px;width: 600px;margin: 0;padding: 0;line-height: 100%;outline: none;text-decoration: none;" width="600" height="130"></a>
2669 +
2670 + <!-- // End: Standard Header Image \\ -->
2671 +
2672 + </td>
2673 + </tr>
2674 + </table>
2675 +
2676 + <!-- // End: Template Header \\ -->
2677 +
2678 + </td>
2679 + </tr>
2680 + <tr>
2681 + <td align="center" valign="top" style="border-collapse: collapse;">
2682 +
2683 + <!-- // Begin: Template Body \\ -->
2684 +
2685 + <table border="0" cellpadding="0" cellspacing="0" width="600" id="templateBody">
2686 + <tr>
2687 + <td valign="top" class="bodyContent" style="border-collapse: collapse;background-color: #FFFFFF;">
2688 +
2689 + <!-- // Begin: Standard Content \\ -->
2690 +EOT;
2691 +
2692 + $mail_send[ 'body' ] = <<<EOT
2693 + <table border="0" cellpadding="20" cellspacing="0" width="100%">
2694 + <tr>
2695 + <td valign="top" style="border-collapse: collapse;">
2696 + <div style="color: #505050;font-family: Arial;font-size: 14px;line-height: 150%;text-align: left;"> Hi MainWP user, <br><br>
2697 + <b style="color: rgb(127, 177, 0); font-family: Helvetica, Sans; font-size: medium; line-height: normal;"> {$title} </b><br>
2698 + <br>{$body}<br>
2699 + </div>
2700 + </td>
2701 + </tr>
2702 + </table>
2703 +EOT;
2704 +
2705 + $mail_send[ 'footer' ] = <<<EOT
2706 + <!-- // End: Standard Content \\ -->
2707 +
2708 + </td>
2709 + </tr>
2710 + </table>
2711 +
2712 + <!-- // End: Template Body \\ -->
2713 +
2714 + </td>
2715 + </tr>
2716 + <tr>
2717 + <td align="center" valign="top" style="border-collapse: collapse;">
2718 +
2719 + <!-- // Begin: Template Footer \\ -->
2720 +
2721 + <table border="0" cellpadding="10" cellspacing="0" width="600" id="templateFooter" style="background-color: #1d1b1c;border-top: 4px solid #7fb100;">
2722 + <tr>
2723 + <td valign="top" class="footerContent" style="border-collapse: collapse;">
2724 +
2725 + <!-- // Begin: Standard Footer \\ -->
2726 +
2727 + <table border="0" cellpadding="10" cellspacing="0" width="100%">
2728 + <tr>
2729 + <td valign="middle" id="social" style="border-collapse: collapse;background-color: #1d1b1c;border: 0;">
2730 + <div style="color: #b8b8b8;font-family: Arial;font-size: 12px;line-height: 125%;text-align: center;">
2731 + <style type="text/css">
2732 + #mainwp-links a {
2733 + text-transform: uppercase;
2734 + text-decoration: none;
2735 + color: #7fb100 ;
2736 + }
2737 + </style>
2738 + <div class="tpl-content-highlight" id="mainwp-links" style="color: #b8b8b8;font-family: Arial;font-size: 12px;line-height: 125%;text-align: center;">
2739 + <a href="https://mainwp.com" target="_self" style="color: #7fb100;font-weight: normal;text-decoration: none;text-transform: uppercase;">MainWP</a> | <a href="https://mainwp.com/mainwp-extensions/" target="_self" style="color: #7fb100;font-weight: normal;text-decoration: none;text-transform: uppercase;">Extensions</a> | <a href="https://mainwp.com/help/" target="_self" style="color: #7fb100;font-weight: normal;text-decoration:none;text-transform: uppercase;">Documentation</a> | <a href="https://mainwp.com/mainwp-blog/" target="_self" style="color: #7fb100;font-weight: normal;text-decoration: none;text-transform: uppercase;">Blog</a> | <a href="http://codex.mainwp.com" target="_self" style="color: #7fb100;font-weight: normal;text-decoration: none;text-transform: uppercase;">Codex</a> | <a href="https://mainwp.com/support/" target="_self" style="color: #7fb100;font-weight: normal;text-decoration: none;text-transform: uppercase;">Support</a></div>
2740 +
2741 + <hr><br>
2742 + <a href="https://twitter.com/mymainwp" target="_blank" style="color: #336699;font-weight: normal;text-decoration: underline;">Follow us on Twitter</a> | <a href="https://www.facebook.com/mainwp" style="color:#336699;font-weight: normal;text-decoration: underline;">Friend us on Facebook</a>
2743 + </td>
2744 + </tr>
2745 + <tr>
2746 + <td valign="top" style="border-collapse: collapse;">
2747 + <div style="color: #b8b8b8;font-family: Arial;font-size: 12px;line-height: 125%;text-align: center;"><div style="text-align: left;color: #b8b8b8;font-family: Arial;font-size: 12px;line-height: 125%;"><em>Copyright &copy; {$current_year} MainWP, All rights reserved.</em><br></div></div>
2748 + </td>
2749 + </tr>
2750 + </table>
2751 +
2752 + <!-- // End: Standard Footer \\ -->
2753 +
2754 + </td>
2755 + </tr>
2756 + </table>
2757 +
2758 + <!-- // End: Template Footer \\ -->
2759 +
2760 + </td>
2761 + </tr>
2762 + </table>
2763 + <br>
2764 + </td>
2765 + </tr>
2766 + </table>
2767 + </center>
2768 + </body>
2769 +</html>
2770 +EOT;
1481 2771 }
2772 + $mail_send = apply_filters( 'mainwp_format_email', $mail_send );
2773 + return $mail_send[ 'header' ] . $mail_send[ 'body' ] . $mail_send[ 'footer' ];
2774 + }
1482 2775
1483 - if ( '/' !== substr( $url, - 1 ) ) {
1484 - $url .= '/';
1485 - }
2776 + public static function endSession() {
2777 + session_write_close();
2778 + if ( ob_get_length() > 0 ) {
2779 + ob_end_flush();
2780 + }
2781 + }
1486 2782
1487 - $favi_url = $url . $favi;
2783 + public static function getLockIdentifier( $pLockName ) {
2784 + if ( ( $pLockName == null ) || ( $pLockName == false ) ) {
2785 + return false;
2786 + }
1488 2787
1489 - $content = MainWP_Connect::get_file_content( $favi_url );
2788 + if ( function_exists( 'sem_get' ) ) {
2789 + return sem_get( $pLockName );
2790 + } else {
2791 + $fh = @fopen( sys_get_temp_dir() . DIRECTORY_SEPARATOR . 'lock' . $pLockName . '.txt', 'w+' );
2792 + if ( !$fh ) {
2793 + return false;
2794 + }
1490 2795
1491 - if ( empty( $content ) && 'favicon.ico' === $favi ) {
1492 - $favi_url = $url . 'favicon.png';
1493 - $content = MainWP_Connect::get_file_content( $favi_url ); // try other file.
1494 - }
2796 + return $fh;
2797 + }
1495 2798
1496 - if ( ! empty( $content ) ) {
2799 + return false;
2800 + }
1497 2801
1498 - MainWP_System_Utility::get_wp_file_system();
2802 + public static function lock( $pIdentifier ) {
2803 + if ( ( $pIdentifier == null ) || ( $pIdentifier == false ) ) {
2804 + return false;
2805 + }
1499 2806
1500 - global $wp_filesystem;
2807 + if ( function_exists( 'sem_acquire' ) ) {
2808 + return sem_acquire( $pIdentifier );
2809 + } else {
2810 + //Retry lock 3 times
2811 + for ( $i = 0; $i < 3; $i ++ ) {
2812 + if ( @flock( $pIdentifier, LOCK_EX ) ) {
2813 + // acquire an exclusive lock
2814 + return $pIdentifier;
2815 + } else {
2816 + //Sleep before lock retry
2817 + sleep( 1 );
2818 + }
2819 + }
1501 2820
1502 - $dirs = MainWP_System_Utility::get_mainwp_dir( 'icons', true );
1503 - $iconsDir = $dirs[0];
1504 - if ( $favi ) {
2821 + return false;
2822 + }
1505 2823
1506 - $tmp = explode( '.', $favi );
1507 - if ( 2 !== count( $tmp ) ) {
1508 - return false;
1509 - }
2824 + return false;
2825 + }
1510 2826
1511 - $favi_ext = $tmp[1];
2827 + public static function release( $pIdentifier ) {
2828 + if ( ( $pIdentifier == null ) || ( $pIdentifier == false ) ) {
2829 + return false;
2830 + }
1512 2831
1513 - if ( empty( $item_id ) ) {
1514 - $item_id = time() . '-' . wp_rand( 100, 999 );
1515 - }
1516 - if ( ! empty( $file_prefix ) ) {
1517 - $filename = $file_prefix . $item_id . '.' . $favi_ext;
1518 - } else {
1519 - $filename = 'favi-' . $item_id . '.' . $favi_ext;
1520 - }
2832 + if ( function_exists( 'sem_release' ) ) {
2833 + return sem_release( $pIdentifier );
2834 + } else {
2835 + @flock( $pIdentifier, LOCK_UN ); // release the lock
2836 + @fclose( $pIdentifier );
2837 + }
1521 2838
1522 - $size = $wp_filesystem->put_contents( $iconsDir . $filename, $content ); // phpcs:ignore --
1523 - if ( $size ) {
1524 - MainWP_Logger::instance()->debug( 'Icon Cost Product size :: ' . $size );
1525 - return array(
1526 - 'result' => 'success',
1527 - 'file' => $filename,
1528 - 'dir' => $iconsDir,
1529 - );
1530 - } else {
1531 - return array( 'error' => 'Save icon file failed.' );
1532 - }
1533 - }
1534 - return false;
2839 + return false;
2840 + }
2841 +
2842 + public static function getTimestamp( $timestamp ) {
2843 + $gmtOffset = get_option( 'gmt_offset' );
2844 +
2845 + return ( $gmtOffset ? ( $gmtOffset * HOUR_IN_SECONDS ) + $timestamp : $timestamp );
2846 + }
2847 +
2848 + public static function date( $format ) {
2849 + return date( $format, self::getTimestamp( time() ) );
2850 + }
2851 +
2852 + public static function formatTimestamp( $timestamp ) {
2853 + return date_i18n( get_option( 'date_format' ) . ' ' . get_option( 'time_format' ), $timestamp );
2854 + }
2855 +
2856 + public static function human_filesize( $bytes, $decimals = 2 ) {
2857 + $size = array( 'B', 'kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB' );
2858 + $factor = floor( ( strlen( $bytes ) - 1 ) / 3 );
2859 +
2860 + return sprintf( "%.{$decimals}f", $bytes / pow( 1024, $factor ) ) . @$size[ $factor ];
2861 + }
2862 +
2863 + public static function mapSite( &$website, $keys ) {
2864 + $outputSite = array();
2865 + foreach ( $keys as $key ) {
2866 + $outputSite[ $key ] = $website->$key;
2867 + }
2868 +
2869 + return (object) $outputSite;
2870 + }
2871 +
2872 + public static function mapSiteArray( &$website, $keys ) {
2873 + $outputSite = array();
2874 + foreach ( $keys as $key ) {
2875 + $outputSite[ $key ] = $website->$key;
2876 + }
2877 +
2878 + return $outputSite;
2879 + }
2880 +
2881 + public static function can_edit_website( &$website ) {
2882 + if ( $website == null ) {
2883 + return false;
2884 + }
2885 +
2886 + //Everyone may change this website
2887 + if ( MainWP_System::Instance()->isSingleUser() ) {
2888 + return true;
2889 + }
2890 +
2891 + global $current_user;
2892 +
2893 + return ( $website->userid == $current_user->ID );
2894 + }
2895 +
2896 + public static function can_edit_group( &$group ) {
2897 + if ( $group == null ) {
2898 + return false;
2899 + }
2900 +
2901 + //Everyone may change this website
2902 + if ( MainWP_System::Instance()->isSingleUser() ) {
2903 + return true;
2904 + }
2905 +
2906 + global $current_user;
2907 +
2908 + return ( $group->userid == $current_user->ID );
2909 + }
2910 +
2911 + public static function can_edit_backuptask( &$task ) {
2912 + if ( $task == null ) {
2913 + return false;
2914 + }
2915 +
2916 + if ( MainWP_System::Instance()->isSingleUser() ) {
2917 + return true;
2918 + }
2919 +
2920 + global $current_user;
2921 +
2922 + return ( $task->userid == $current_user->ID );
2923 + }
2924 +
2925 + public static function get_current_wpid() {
2926 + global $current_user;
2927 +
2928 + return $current_user->current_site_id;
2929 + }
2930 +
2931 + public static function set_current_wpid( $wpid ) {
2932 + global $current_user;
2933 + $current_user->current_site_id = $wpid;
2934 + }
2935 +
2936 + public static function array_merge( $arr1, $arr2 ) {
2937 + if ( !is_array( $arr1 ) && !is_array( $arr2 ) ) {
2938 + return array();
2939 + }
2940 + if ( !is_array( $arr1 ) ) {
2941 + return $arr2;
2942 + }
2943 + if ( !is_array( $arr2 ) ) {
2944 + return $arr1;
2945 + }
2946 +
2947 + $output = array();
2948 + foreach ( $arr1 as $el ) {
2949 + $output[] = $el;
2950 + }
2951 + foreach ( $arr2 as $el ) {
2952 + $output[] = $el;
2953 + }
2954 +
2955 + return $output;
2956 + }
2957 +
2958 + public static function getCronSchedules( $schedules ) {
2959 + $schedules[ '5minutely' ] = array(
2960 + 'interval' => 5 * 60, // 5minutes in seconds
2961 + 'display' => __( 'Once every 5 minutes', 'mainwp' ),
2962 + );
2963 + $schedules[ 'minutely' ] = array(
2964 + 'interval' => 1 * 60, // 1minute in seconds
2965 + 'display' => __( 'Once every minute', 'mainwp' ),
2966 + );
2967 +
2968 + return $schedules;
2969 + }
2970 +
2971 + public static function getWebsitesAutomaticUpdateTime() {
2972 + $lastAutomaticUpdate = MainWP_DB::Instance()->getWebsitesLastAutomaticSync();
2973 +
2974 + if ( $lastAutomaticUpdate == 0 ) {
2975 + $nextAutomaticUpdate = 'Any minute';
2976 + } else if ( MainWP_DB::Instance()->getWebsitesCountWhereDtsAutomaticSyncSmallerThenStart() > 0 || MainWP_DB::Instance()->getWebsitesCheckUpdatesCount() > 0 ) {
2977 + $nextAutomaticUpdate = 'Processing your websites.';
2978 + } else {
2979 + $nextAutomaticUpdate = MainWP_Utility::formatTimestamp( MainWP_Utility::getTimestamp( mktime( 0, 0, 0, date( 'n' ), date( 'j' ) + 1 ) ) );
2980 + }
2981 +
2982 + if ( $lastAutomaticUpdate == 0 ) {
2983 + $lastAutomaticUpdate = 'Never';
2984 + } else {
2985 + $lastAutomaticUpdate = MainWP_Utility::formatTimestamp( MainWP_Utility::getTimestamp( $lastAutomaticUpdate ) );
2986 + }
2987 +
2988 + return array(
2989 + 'last' => $lastAutomaticUpdate,
2990 + 'next' => $nextAutomaticUpdate
2991 + );
2992 + }
2993 +
2994 + public static function mime_content_type( $filename ) {
2995 + if ( function_exists( 'finfo_open' ) ) {
2996 + $finfo = finfo_open( FILEINFO_MIME );
2997 + $mimetype = finfo_file( $finfo, $filename );
2998 + finfo_close( $finfo );
2999 +
3000 + return $mimetype;
3001 + }
3002 +
3003 + if ( function_exists( 'mime_content_type' ) ) {
3004 + return mime_content_type( $filename );
3005 + }
3006 +
3007 + $mime_types = array(
3008 + 'txt' => 'text/plain',
3009 + 'htm' => 'text/html',
3010 + 'html' => 'text/html',
3011 + 'php' => 'text/html',
3012 + 'css' => 'text/css',
3013 + 'js' => 'application/javascript',
3014 + 'json' => 'application/json',
3015 + 'xml' => 'application/xml',
3016 + 'swf' => 'application/x-shockwave-flash',
3017 + 'flv' => 'video/x-flv',
3018 + // images
3019 + 'png' => 'image/png',
3020 + 'jpe' => 'image/jpeg',
3021 + 'jpeg' => 'image/jpeg',
3022 + 'jpg' => 'image/jpeg',
3023 + 'gif' => 'image/gif',
3024 + 'bmp' => 'image/bmp',
3025 + 'ico' => 'image/vnd.microsoft.icon',
3026 + 'tiff' => 'image/tiff',
3027 + 'tif' => 'image/tiff',
3028 + 'svg' => 'image/svg+xml',
3029 + 'svgz' => 'image/svg+xml',
3030 + // archives
3031 + 'zip' => 'application/zip',
3032 + 'rar' => 'application/x-rar-compressed',
3033 + 'exe' => 'application/x-msdownload',
3034 + 'msi' => 'application/x-msdownload',
3035 + 'cab' => 'application/vnd.ms-cab-compressed',
3036 + // audio/video
3037 + 'mp3' => 'audio/mpeg',
3038 + 'qt' => 'video/quicktime',
3039 + 'mov' => 'video/quicktime',
3040 + // adobe
3041 + 'pdf' => 'application/pdf',
3042 + 'psd' => 'image/vnd.adobe.photoshop',
3043 + 'ai' => 'application/postscript',
3044 + 'eps' => 'application/postscript',
3045 + 'ps' => 'application/postscript',
3046 + // ms office
3047 + 'doc' => 'application/msword',
3048 + 'rtf' => 'application/rtf',
3049 + 'xls' => 'application/vnd.ms-excel',
3050 + 'ppt' => 'application/vnd.ms-powerpoint',
3051 + // open office
3052 + 'odt' => 'application/vnd.oasis.opendocument.text',
3053 + 'ods' => 'application/vnd.oasis.opendocument.spreadsheet',
3054 + );
3055 +
3056 + $ext = strtolower( array_pop( explode( '.', $filename ) ) );
3057 + if ( array_key_exists( $ext, $mime_types ) ) {
3058 + return $mime_types[ $ext ];
3059 + }
3060 +
3061 + return 'application/octet-stream';
3062 + }
3063 +
3064 + static function update_option( $option_name, $option_value ) {
3065 + $success = add_option( $option_name, $option_value, '', 'no' );
3066 +
3067 + if ( !$success ) {
3068 + $success = update_option( $option_name, $option_value );
3069 + }
3070 +
3071 + return $success;
3072 + }
3073 +
3074 + static function fix_option( $option_name ) {
3075 + global $wpdb;
3076 +
3077 + if ( 'yes' == $wpdb->get_var( "SELECT autoload FROM $wpdb->options WHERE option_name = '" . $option_name . "'" ) ) {
3078 + $option_value = get_option( $option_name );
3079 + delete_option( $option_name );
3080 + add_option( $option_name, $option_value, null, 'no' );
3081 + }
3082 + }
3083 +
3084 + static function get_resource_id( $resource ) {
3085 + if ( !is_resource( $resource ) ) {
3086 + return false;
3087 + }
3088 +
3089 + $resourceString = (string) $resource;
3090 + $exploded = explode( '#', $resourceString );
3091 + $result = array_pop( $exploded );
3092 +
3093 + return $result;
3094 + }
3095 +
3096 + public static function getFileParameter( &$website ) {
3097 + if ( !isset( $website->version ) || empty( $website->version ) ) {
3098 + return 'file';
3099 + }
3100 + if ( version_compare( '0.29.13', $website->version ) < 0 ) {
3101 + return 'f';
3102 + }
3103 +
3104 + return 'file';
3105 + }
3106 +
3107 + public static function removePreSlashSpaces( $text ) {
3108 + while ( stristr( $text, ' /' ) ) {
3109 + $text = str_replace( ' /', '/', $text );
3110 + }
3111 +
3112 + return $text;
3113 + }
3114 +
3115 + public static function removeHttpPrefix( $pUrl, $pTrimSlashes = false ) {
3116 + return str_replace( array( 'http:' . ( $pTrimSlashes ? '//' : '' ), 'https:' . ( $pTrimSlashes ? '//' : '' ) ), array( '', '' ), $pUrl );
3117 + }
3118 +
3119 + public static function removeHttpWWWPrefix( $pUrl ) {
3120 + $pUrl = self::removeHttpPrefix($pUrl, true);
3121 + return str_replace( 'www' , '', $pUrl );
3122 + }
3123 +
3124 + public static function isArchive( $pFileName, $pPrefix = '', $pSuffix = '' ) {
3125 + return preg_match( '/' . $pPrefix . '(.*).(zip|tar|tar.gz|tar.bz2)' . $pSuffix . '$/', $pFileName );
3126 + }
3127 +
3128 + public static function isSQLFile( $pFileName ) {
3129 + return preg_match( '/(.*).sql$/', $pFileName ) || self::isSQLArchive( $pFileName );
3130 + }
3131 +
3132 + public static function isSQLArchive( $pFileName ) {
3133 + return preg_match( '/(.*).sql.(zip|tar|tar.gz|tar.bz2)$/', $pFileName );
3134 + }
3135 +
3136 + public static function getCurrentArchiveExtension( $website = false, $task = false ) {
3137 + $useSite = true;
3138 + if ( $task != false ) {
3139 + if ( $task->archiveFormat == 'global' ) {
3140 + $useGlobal = true;
3141 + $useSite = false;
3142 + } else if ( $task->archiveFormat == '' || $task->archiveFormat == 'site' ) {
3143 + $useGlobal = false;
3144 + $useSite = true;
3145 + } else {
3146 + $archiveFormat = $task->archiveFormat;
3147 + $useGlobal = false;
3148 + $useSite = false;
3149 + }
3150 + }
3151 +
3152 + if ( $useSite ) {
3153 + if ( $website == false ) {
3154 + $useGlobal = true;
3155 + } else {
3156 + $backupSettings = MainWP_DB::Instance()->getWebsiteBackupSettings( $website->id );
3157 + $archiveFormat = $backupSettings->archiveFormat;
3158 + $useGlobal = ( $archiveFormat == 'global' );
3159 + }
3160 + }
3161 +
3162 + if ( $useGlobal ) {
3163 + $archiveFormat = get_option( 'mainwp_archiveFormat' );
3164 + if ( $archiveFormat === false ) {
3165 + $archiveFormat = 'tar.gz';
3166 + }
3167 + }
3168 +
3169 + return $archiveFormat;
3170 + }
3171 +
3172 + public static function getRealExtension( $path ) {
3173 + $checks = array( '.sql.zip', '.sql.tar', '.sql.tar.gz', '.sql.tar.bz2', '.tar.gz', '.tar.bz2' );
3174 + foreach ( $checks as $check ) {
3175 + if ( self::endsWith( $path, $check ) ) {
3176 + return $check;
3177 + }
3178 + }
3179 +
3180 + return '.' . pathinfo( $path, PATHINFO_EXTENSION );
3181 + }
3182 +
3183 + public static function sanitize_file_name( $filename ) {
3184 + $filename = str_replace( array( '|', '/', '\\', ' ', ':' ), array( '-', '-', '-', '-', '-' ), $filename );
3185 +
3186 + return sanitize_file_name( $filename );
3187 + }
3188 +
3189 + public static function normalize_filename( $s ) {
3190 + // maps German (umlauts) and other European characters onto two characters before just removing diacritics
3191 + $s = preg_replace( '@\x{00c4}@u', 'A', $s ); // umlaut Ä => A
3192 + $s = preg_replace( '@\x{00d6}@u', 'O', $s ); // umlaut Ö => O
3193 + $s = preg_replace( '@\x{00dc}@u', 'U', $s ); // umlaut Ü => U
3194 + $s = preg_replace( '@\x{00cb}@u', 'E', $s ); // umlaut Ë => E
3195 + $s = preg_replace( '@\x{00e4}@u', 'a', $s ); // umlaut ä => a
3196 + $s = preg_replace( '@\x{00f6}@u', 'o', $s ); // umlaut ö => o
3197 + $s = preg_replace( '@\x{00fc}@u', 'u', $s ); // umlaut ü => u
3198 + $s = preg_replace( '@\x{00eb}@u', 'e', $s ); // umlaut ë => e
3199 + $s = preg_replace( '@\x{00f1}@u', 'n', $s ); // ñ => n
3200 + $s = preg_replace( '@\x{00ff}@u', 'y', $s ); // ÿ => y
3201 + return $s;
3202 + }
3203 +
3204 +
3205 + public static function esc_content( $content, $type = 'note' ) {
3206 + if ( $type == 'note' ) {
3207 +
3208 + $allowed_html = array(
3209 + 'a' => array(
3210 + 'href' => array(),
3211 + 'title' => array()
3212 + ),
3213 + 'br' => array(),
3214 + 'em' => array(),
3215 + 'strong' => array(),
3216 + 'p' => array(),
3217 + 'hr' => array(),
3218 + 'ul' => array(),
3219 + 'ol' => array(),
3220 + 'li' => array(),
3221 + 'h1' => array(),
3222 + 'h2' => array(),
3223 + );
3224 +
3225 + $content = wp_kses( $content, $allowed_html );
3226 +
1535 3227 } else {
1536 - return array( 'error' => esc_html__( 'Download icon file failed', 'mainwp' ) );
3228 + $content = wp_kses_post( $content );
1537 3229 }
3230 +
3231 + return $content;
1538 3232 }
1539 3233
1540 - /**
1541 - * Method get_saved_favicon_url()
1542 - *
1543 - * @param string $favi Favicon file name.
1544 - *
1545 - * @return mixed $faviurl Favicon URL.
1546 - */
1547 - public static function get_saved_favicon_url( $favi ) {
1548 - $faviurl = '';
1549 - if ( ! empty( $favi ) ) {
1550 - $dirs = MainWP_System_Utility::get_icons_dir();
1551 - if ( file_exists( $dirs[0] . $favi ) ) {
1552 - $faviurl = $dirs[1] . $favi;
1553 - } else {
1554 - $faviurl = '';
1555 - }
1556 - }
1557 - return $faviurl;
3234 + public static function showUserTip( $tip_id ) {
3235 + global $current_user;
3236 +
3237 + if ( get_option( 'mainwp_hide_tips', 1 ) ) {
3238 + return false;
3239 + }
3240 +
3241 + if ( $user_id = $current_user->ID ) {
3242 + $reset_tips = get_option( 'mainwp_reset_user_tips' );
3243 + if ( !is_array( $reset_tips ) ) {
3244 + $reset_tips = array();
3245 + }
3246 + if ( !isset( $reset_tips[ $user_id ] ) ) {
3247 + $reset_tips[ $user_id ] = 1;
3248 + update_option( 'mainwp_reset_user_tips', $reset_tips );
3249 + update_user_option( $user_id, 'mainwp_hide_user_tips', array() );
3250 +
3251 + return true;
3252 + }
3253 +
3254 + $hide_usertips = get_user_option( 'mainwp_hide_user_tips' );
3255 + if ( !is_array( $hide_usertips ) ) {
3256 + $hide_usertips = array();
3257 + }
3258 + if ( isset( $hide_usertips[ $tip_id ] ) ) {
3259 + return false;
3260 + }
3261 + }
3262 +
3263 + return true;
3264 + }
3265 +
3266 + public static function showMainWPMessage( $type, $notice_id ) {
3267 + $status = get_user_option( 'mainwp_notice_saved_status' );
3268 + if ( !is_array( $status ) ) {
3269 + $status = array();
3270 + }
3271 + if ( isset( $status[ $notice_id ] ) ) {
3272 + return false;
3273 + }
3274 + return true;
3275 + }
3276 +
3277 + public static function resetUserCookie( $what, $value = '' ) {
3278 + global $current_user;
3279 + if ( $user_id = $current_user->ID ) {
3280 + $reset_cookies = get_option( 'mainwp_reset_user_cookies' );
3281 + if ( !is_array( $reset_cookies ) ) {
3282 + $reset_cookies = array();
3283 + }
3284 +
3285 + if ( !isset( $reset_cookies[ $user_id ] ) || !isset( $reset_cookies[ $user_id ][ $what ] ) ) {
3286 + $reset_cookies[ $user_id ][ $what ] = 1;
3287 + MainWP_Utility::update_option( 'mainwp_reset_user_cookies', $reset_cookies );
3288 + update_user_option( $user_id, 'mainwp_saved_user_cookies', array() );
3289 +
3290 + return false;
3291 + }
3292 +
3293 + $user_cookies = get_user_option( 'mainwp_saved_user_cookies' );
3294 + if ( !is_array( $user_cookies ) ) {
3295 + $user_cookies = array();
3296 + }
3297 + if ( !isset( $user_cookies[ $what ] ) ) {
3298 + return false;
3299 + }
3300 + }
3301 +
3302 + return true;
3303 + }
3304 +
3305 + public static function get_favico_url( $website ) {
3306 + $favi = MainWP_DB::Instance()->getWebsiteOption( $website, 'favi_icon', '' );
3307 + $faviurl = '';
3308 +
3309 + if ( !empty( $favi ) ) {
3310 + if ( false !== strpos( $favi, 'favi-' . $website->id . '-' ) ) {
3311 + $dirs = self::getIconsDir();
3312 + if ( file_exists( $dirs[ 0 ] . $favi ) ) {
3313 + $faviurl = $dirs[ 1 ] . $favi;
3314 + } else {
3315 + $faviurl = '';
3316 + }
3317 + } else if ( ( strpos( $favi, '//' ) === 0 ) || ( strpos( $favi, 'http' ) === 0 ) ) {
3318 + $faviurl = $favi;
3319 + } else {
3320 + $faviurl = $website->url . $favi;
3321 + $faviurl = MainWP_Utility::removeHttpPrefix( $faviurl );
3322 + }
3323 + }
3324 + if ( empty( $faviurl ) ) {
3325 + $faviurl = MAINWP_PLUGIN_URL . 'assests/images/sitefavi.png';
3326 + }
3327 +
3328 + return $faviurl;
3329 + }
3330 +
3331 + public static function getCURLSSLVersion( $sslVersion ) {
3332 + switch ( $sslVersion ) {
3333 + case '1.x':
3334 + return 1; //CURL_SSLVERSION_TLSv1;
3335 + case '2':
3336 + return 2; //CURL_SSLVERSION_SSLv2;
3337 + case '3':
3338 + return 3; //CURL_SSLVERSION_SSLv3;
3339 + case '1.0':
3340 + return 4; //CURL_SSLVERSION_TLSv1_0;
3341 + case '1.1':
3342 + return 5; //CURL_SSLVERSION_TLSv1_1;
3343 + case '1.2':
3344 + return 6; //CURL_SSLVERSION_TLSv1_2;
3345 + default:
3346 + return 0; //CURL_SSLVERSION_DEFAULT;
3347 + }
3348 + }
3349 +
3350 + public static function array_sort( &$array, $key, $sort_flag = SORT_STRING ) {
3351 + $sorter = array();
3352 + $ret = array();
3353 + reset( $array );
3354 + foreach ( $array as $ii => $val ) {
3355 + $sorter[ $ii ] = $val[ $key ];
3356 + }
3357 + asort( $sorter, $sort_flag );
3358 + foreach ( $sorter as $ii => $val ) {
3359 + $ret[ $ii ] = $array[ $ii ];
3360 + }
3361 + $array = $ret;
3362 + }
3363 +
3364 + public static function enabled_wp_seo() {
3365 + if ( self::$enabled_wp_seo === null ) {
3366 + self::$enabled_wp_seo = is_plugin_active( 'wordpress-seo-extension/wordpress-seo-extension.php' );
3367 + }
3368 + return self::$enabled_wp_seo;
3369 + }
3370 +
3371 +
3372 + public static function get_page_id( $screen = null) {
3373 +
3374 + if ( empty( $screen ) ) {
3375 + $screen = get_current_screen();
3376 + } elseif ( is_string( $screen ) ) {
3377 + $screen = convert_to_screen( $screen );
3378 + }
3379 +
3380 + if ( ! isset( $screen->id ) ) {
3381 + return;
3382 + }
3383 +
3384 + $page = $screen->id;
3385 +
3386 + return $page;
1558 3387 }
1559 3388
1560 - /**
1561 - * Method delete_saved_favicon()
1562 - *
1563 - * @param string $favi Favicon file name.
1564 - *
1565 - * @return bool Success result.
1566 - */
1567 - public static function delete_saved_favicon( $favi ) {
1568 - if ( ! empty( $favi ) ) {
1569 - $hasWPFileSystem = MainWP_System_Utility::get_wp_file_system();
1570 - global $wp_filesystem;
1571 - $dirs = MainWP_System_Utility::get_icons_dir();
1572 - if ( $hasWPFileSystem && $wp_filesystem->exists( $dirs[0] . $favi ) ) {
1573 - $wp_filesystem->delete( $dirs[0] . $favi );
1574 - return true;
1575 - }
1576 - }
1577 - return false;
1578 - }
3389 + public static function gen_hidden_column( $col, $hidden ) {
3390 + if ( !is_array( $hidden ) )
3391 + return;
3392 + if ( in_array( $col, $hidden ) ) {
3393 + echo 'hidden';
3394 + return;
3395 + }
3396 + return;
3397 + }
1579 3398
1580 - /**
1581 - * Delete icon file.
1582 - *
1583 - * @param string $sub_dir Sub dir file icon.
1584 - * @param string $cost_icon file icon.
1585 - */
1586 - public function delete_uploaded_icon_file( $sub_dir, $cost_icon ) {
1587 - $valid_file = 0 === validate_file( $cost_icon ) ? true : false;
1588 - if ( $valid_file ) {
1589 - $dirs = MainWP_System_Utility::get_mainwp_dir( $sub_dir, true );
1590 - $f = $dirs[0] . $cost_icon;
1591 - if ( file_exists( $f ) ) {
1592 - wp_delete_file( $f );
1593 - }
1594 - }
1595 - }
3399 + static function generate_random_string( $length = 8 ) {
1596 3400
1597 - /**
1598 - * Method get_table_orders().
1599 - *
1600 - * @param array $data table data.
1601 - */
1602 - public function get_table_orders( $data ) {
3401 + $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
1603 3402
1604 - $values = array(
1605 - 'orderby' => null,
1606 - 'order' => null,
1607 - );
3403 + $charactersLength = strlen( $characters );
1608 3404
1609 - if ( isset( $data['order'] ) ) {
1610 - $columns = isset( $data['columns'] ) ? wp_unslash( $data['columns'] ) : array();
1611 - $ord_col = isset( $data['order'][0]['column'] ) ? sanitize_text_field( wp_unslash( $data['order'][0]['column'] ) ) : '';
1612 - if ( isset( $columns[ $ord_col ] ) ) {
1613 - $values = array(
1614 - 'orderby' => isset( $columns[ $ord_col ]['data'] ) ? sanitize_text_field( wp_unslash( $columns[ $ord_col ]['data'] ) ) : '',
1615 - 'order' => isset( $data['order'][0]['dir'] ) ? sanitize_text_field( wp_unslash( $data['order'][0]['dir'] ) ) : '',
1616 - );
1617 - }
1618 - }
3405 + $randomString = '';
1619 3406
1620 - return $values;
1621 - }
3407 + for ( $i = 0; $i < $length; $i++ ) {
3408 +
3409 + $randomString .= $characters[ rand( 0, $charactersLength - 1 ) ];
3410 + }
3411 +
3412 + return $randomString;
3413 + }
3414 +
1622 3415 }