function mainwp_createbackup_getfilesize() { $this->secure_request('mainwp_createbackup_getfilesize'); try { if (!isset($_POST['siteId'])) { throw new Exception(__('No site given', 'mainwp-child')); } $siteId = $_POST['siteId']; $fileName = $_POST['fileName']; $fileNameUID = $_POST['fileNameUID']; $type = $_POST['type']; $website = MainWPDB::Instance()->getWebsiteById($siteId); if (!$website) { throw new Exception(__('No site given', 'mainwp-child')); } MainWPUtility::endSession(); //Send request to the childsite! $result = MainWPUtility::fetchUrlAuthed($website, 'createBackupPoll', array('fileName' => $fileName, 'fileNameUID' => $fileNameUID, 'type' => $type)); if (!isset($result['size'])) { throw new Exception(__('Invalid response', 'mainwp-child')); } if (MainWPUtility::ctype_digit($result['size'])) { $output = array('size' => $result['size']); } else { $output = array(); } } catch (Exception $e) { $output = array('error' => $e->getMessage()); } die(json_encode($output)); }
public static function syncSite() { $website = null; if (isset($_POST['wp_id'])) { $website = MainWPDB::Instance()->getWebsiteById($_POST['wp_id']); } if ($website == null) { die(json_encode(array('error' => 'Invalid Request'))); } $maxRequestsInThirtySeconds = get_option('mainwp_maximumRequests'); MainWPUtility::endSession(); $semLock = '103218'; //SNSyncLock // $identifier = null; // if ($maxRequestsInThirtySeconds != false || $maxRequestsInThirtySeconds != 0) // { // //Lock // $identifier = MainWPUtility::getLockIdentifier($semLock); // MainWPUtility::lock($identifier); // // $req = MainWPDB::Instance()->getRequestsSince(30 / $maxRequestsInThirtySeconds); // MainWPUtility::endSession(); // // while ($req >= 1) // { // MainWPUtility::release($identifier); // //Unlock // sleep(2); // // //Lock // MainWPUtility::lock($identifier); // $req = MainWPDB::Instance()->getRequestsSince(30 / $maxRequestsInThirtySeconds); // MainWPUtility::endSession(); // } // } MainWPDB::Instance()->updateWebsiteSyncValues($website->id, array('dtsSyncStart' => time())); MainWPUtility::endSession(); //Unlock // MainWPUtility::release($identifier); if (MainWPSync::syncSite($website)) { die(json_encode(array('result' => 'SUCCESS'))); } $website = MainWPDB::Instance()->getWebsiteById($website->id); die(json_encode(array('error' => $website->sync_errors))); }
public static function performUpload() { MainWPUtility::endSession(); //Fetch info.. $post_data = array('url' => json_encode(explode('||', $_POST['urls'])), 'type' => $_POST['type']); if ($_POST['activatePlugin'] == 'true') { $post_data['activatePlugin'] = 'yes'; } if ($_POST['overwrite'] == 'true') { $post_data['overwrite'] = true; } $output = new stdClass(); $output->ok = array(); $output->errors = array(); $websites = array(MainWPDB::Instance()->getWebsiteById($_POST['siteId'])); MainWPUtility::fetchUrlsAuthed($websites, 'installplugintheme', $post_data, array(MainWPInstallBulk::getClassName(), 'InstallPluginTheme_handler'), $output); die(json_encode($output)); }
public static function backup($pSiteId, $pType, $pSubfolder, $pExclude, $excludebackup, $excludecache, $excludenonwp, $excludezip, $pFilename = null, $pFileNameUID = '', $pArchiveFormat = false, $pMaximumFileDescriptorsOverride = false, $pMaximumFileDescriptorsAuto = false, $pMaximumFileDescriptors = false, $pLoadFilesBeforeZip = false, $pid = false, $append = false) { if (trim($pFilename) == '') { $pFilename = null; } $backup_result = array(); //Creating a backup $website = MainWPDB::Instance()->getWebsiteById($pSiteId); $subfolder = str_replace('%sitename%', MainWPUtility::sanitize($website->name), $pSubfolder); $subfolder = str_replace('%url%', MainWPUtility::sanitize(MainWPUtility::getNiceURL($website->url)), $subfolder); $subfolder = str_replace('%type%', $pType, $subfolder); $subfolder = str_replace('%date%', MainWPUtility::date('Ymd'), $subfolder); $subfolder = str_replace('%task%', '', $subfolder); $subfolder = str_replace('%', '', $subfolder); $subfolder = MainWPUtility::removePreSlashSpaces($subfolder); $subfolder = MainWPUtility::normalize_filename($subfolder); if (!MainWPUtility::can_edit_website($website)) { throw new MainWPException('You are not allowed to backup this site'); } $websiteCleanUrl = $website->url; if (substr($websiteCleanUrl, -1) == '/') { $websiteCleanUrl = substr($websiteCleanUrl, 0, -1); } $websiteCleanUrl = str_replace(array('http://', 'https://', '/'), array('', '', '-'), $websiteCleanUrl); //Normal flow: use website & fallback to global if ($pMaximumFileDescriptorsOverride == false) { if ($website->maximumFileDescriptorsOverride == 1) { $maximumFileDescriptorsAuto = $website->maximumFileDescriptorsAuto == 1; $maximumFileDescriptors = $website->maximumFileDescriptors; } else { $maximumFileDescriptorsAuto = get_option('mainwp_maximumFileDescriptorsAuto'); $maximumFileDescriptors = get_option('mainwp_maximumFileDescriptors'); $maximumFileDescriptors = $maximumFileDescriptors === false ? 150 : $maximumFileDescriptors; } } else { if ($pArchiveFormat != 'global' && $pMaximumFileDescriptorsOverride == 1) { $maximumFileDescriptorsAuto = $pMaximumFileDescriptorsAuto == 1; $maximumFileDescriptors = $pMaximumFileDescriptors; } else { $maximumFileDescriptorsAuto = get_option('mainwp_maximumFileDescriptorsAuto'); $maximumFileDescriptors = get_option('mainwp_maximumFileDescriptors'); $maximumFileDescriptors = $maximumFileDescriptors === false ? 150 : $maximumFileDescriptors; } } $file = str_replace(array('%sitename%', '%url%', '%date%', '%time%', '%type%'), array(MainWPUtility::sanitize($website->name), $websiteCleanUrl, MainWPUtility::date('m-d-Y'), MainWPUtility::date('G\\hi\\ms\\s'), $pType), $pFilename); $file = str_replace('%', '', $file); $file = MainWPUtility::normalize_filename($file); //Normal flow: check site settings & fallback to global if ($pLoadFilesBeforeZip == false) { $loadFilesBeforeZip = $website->loadFilesBeforeZip; if ($loadFilesBeforeZip == 1) { $loadFilesBeforeZip = get_option('mainwp_options_loadFilesBeforeZip'); $loadFilesBeforeZip = $loadFilesBeforeZip == 1 || $loadFilesBeforeZip === false; } else { $loadFilesBeforeZip = $loadFilesBeforeZip == 2; } } else { if ($pArchiveFormat == 'global' || $pLoadFilesBeforeZip == 1) { $loadFilesBeforeZip = get_option('mainwp_options_loadFilesBeforeZip'); $loadFilesBeforeZip = $loadFilesBeforeZip == 1 || $loadFilesBeforeZip === false; } else { $loadFilesBeforeZip = $pLoadFilesBeforeZip == 2; } } //Nomral flow: check site settings & fallback to global if ($pArchiveFormat == false) { $archiveFormat = MainWPUtility::getCurrentArchiveExtension($website); } else { if ($pArchiveFormat == 'global') { $archiveFormat = MainWPUtility::getCurrentArchiveExtension(); } else { $archiveFormat = $pArchiveFormat; } } MainWPUtility::endSession(); $information = MainWPUtility::fetchUrlAuthed($website, 'backup', array('type' => $pType, 'exclude' => $pExclude, 'excludebackup' => $excludebackup, 'excludecache' => $excludecache, 'excludenonwp' => $excludenonwp, 'excludezip' => $excludezip, 'ext' => $archiveFormat, 'file_descriptors_auto' => $maximumFileDescriptorsAuto, 'file_descriptors' => $maximumFileDescriptors, 'loadFilesBeforeZip' => $loadFilesBeforeZip, MainWPUtility::getFileParameter($website) => $file, 'fileUID' => $pFileNameUID, 'pid' => $pid, 'append' => $append ? 1 : 0), false, false, false); do_action('mainwp_managesite_backup', $website, array('type' => $pType), $information); if (isset($information['error'])) { throw new MainWPException($information['error']); } else { if ($pType == 'db' && !$information['db']) { throw new MainWPException('Database backup failed.'); } else { if ($pType == 'full' && !$information['full']) { throw new MainWPException('Full backup failed.'); } else { if (isset($information['db'])) { if ($information['db'] != false) { $backup_result['url'] = $information['db']; $backup_result['type'] = 'db'; } else { if ($information['full'] != false) { $backup_result['url'] = $information['full']; $backup_result['type'] = 'full'; } } if (isset($information['size'])) { $backup_result['size'] = $information['size']; } $backup_result['subfolder'] = $subfolder; $dir = MainWPUtility::getMainWPSpecificDir($pSiteId); $fm_date = MainWPUtility::sanitize_file_name(MainWPUtility::date(get_option('date_format'))); $fm_time = MainWPUtility::sanitize_file_name(MainWPUtility::date(get_option('time_format'))); if ($pType == 'db') { $localBackupFile = $dir . 'db-' . $websiteCleanUrl . '-' . $fm_date . '-' . $fm_time . MainWPUtility::getRealExtension($information['db']); $localRegexFile = 'db-' . $websiteCleanUrl . '-(.*)-(.*).sql(\\.zip|\\.tar|\\.tar\\.gz|\\.tar\\.bz2)?'; } else { $localBackupFile = $dir . 'full-' . $websiteCleanUrl . '-' . $fm_date . '-' . $fm_time . MainWPUtility::getRealExtension($information['full']); $localRegexFile = 'full-' . $websiteCleanUrl . '-(.*)-(.*).(zip|tar|tar.gz|tar.bz2)'; } if ($pFilename != null) { $filename = str_replace(array('%sitename%', '%url%', '%date%', '%time%', '%type%'), array(MainWPUtility::sanitize($website->name), $websiteCleanUrl, $fm_date, $fm_time, $pType), $pFilename); $filename = str_replace('%', '', $filename); $localBackupFile = $dir . $filename; $localBackupFile = MainWPUtility::normalize_filename($localBackupFile); if ($pType == 'db') { $localBackupFile .= MainWPUtility::getRealExtension($information['db']); } else { $localBackupFile .= MainWPUtility::getRealExtension($information['full']); } } $backup_result['local'] = $localBackupFile; $backup_result['regexfile'] = $localRegexFile; return $backup_result; } else { throw new MainWPException('Database backup failed due to an undefined error'); } } } } }
static function _fetchUrl(&$website, $url, $postdata, $checkConstraints = false, $pForceFetch = false, $verifyCertificate = null, $http_user = null, $http_pass = null) { $agent = 'Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)'; if (!$pForceFetch) { //todo: RS: //check if offline } $identifier = null; if ($checkConstraints) { $semLock = '103218'; //SNSyncLock //Lock $identifier = MainWPUtility::getLockIdentifier($semLock); //Check the delays //In MS $minimumDelay = get_option('mainwp_minimumDelay') === false ? 200 : get_option('mainwp_minimumDelay'); if ($minimumDelay > 0) { $minimumDelay = $minimumDelay / 1000; } $minimumIPDelay = get_option('mainwp_minimumIPDelay') === false ? 1000 : get_option('mainwp_minimumIPDelay'); if ($minimumIPDelay > 0) { $minimumIPDelay = $minimumIPDelay / 1000; } MainWPUtility::endSession(); $delay = true; while ($delay) { MainWPUtility::lock($identifier); if ($minimumDelay > 0) { //Check last request overall $lastRequest = MainWPDB::Instance()->getLastRequestTimestamp(); if ($lastRequest > microtime(true) - $minimumDelay) { //Delay! MainWPUtility::release($identifier); usleep(($minimumDelay - (microtime(true) - $lastRequest)) * 1000 * 1000); continue; } } if ($minimumIPDelay > 0 && $website != null) { //Get ip of this site url $ip = MainWPDB::Instance()->getWPIp($website->id); if ($ip != null && $ip != '') { //Check last request for this site $lastRequest = MainWPDB::Instance()->getLastRequestTimestamp($ip); //Check last request for this subnet? if ($lastRequest > microtime(true) - $minimumIPDelay) { //Delay! MainWPUtility::release($identifier); usleep(($minimumIPDelay - (microtime(true) - $lastRequest)) * 1000 * 1000); continue; } } } $delay = false; } //Check the simultaneous requests $maximumRequests = get_option('mainwp_maximumRequests') === false ? 4 : get_option('mainwp_maximumRequests'); $maximumIPRequests = get_option('mainwp_maximumIPRequests') === false ? 1 : get_option('mainwp_maximumIPRequests'); $first = true; $delay = true; while ($delay) { if (!$first) { MainWPUtility::lock($identifier); } else { $first = false; } //Clean old open requests (may have timed out or something..) MainWPDB::Instance()->closeOpenRequests(); if ($maximumRequests > 0) { $nrOfOpenRequests = MainWPDB::Instance()->getNrOfOpenRequests(); if ($nrOfOpenRequests >= $maximumRequests) { //Delay! MainWPUtility::release($identifier); //Wait 200ms usleep(200000); continue; } } if ($maximumIPRequests > 0 && $website != null) { //Get ip of this site url $ip = MainWPDB::Instance()->getWPIp($website->id); if ($ip != null && $ip != '') { $nrOfOpenRequests = MainWPDB::Instance()->getNrOfOpenRequests($ip); if ($nrOfOpenRequests >= $maximumIPRequests) { //Delay! MainWPUtility::release($identifier); //Wait 200ms usleep(200000); continue; } } } $delay = false; } } if ($website != null) { //Log the start of this request! MainWPDB::Instance()->insertOrUpdateRequestLog($website->id, null, microtime(true), null); } if ($identifier != null) { //Unlock MainWPUtility::release($identifier); } $dirs = self::getMainWPDir(); $cookieDir = $dirs[0] . 'cookies'; if (!@is_dir($cookieDir)) { @mkdir($cookieDir, 0777, true); } if (!file_exists($cookieDir . '/.htaccess')) { $file_htaccess = @fopen($cookieDir . '/.htaccess', 'w+'); @fwrite($file_htaccess, 'deny from all'); @fclose($file_htaccess); } if (!file_exists($cookieDir . '/index.php')) { $file_index = @fopen($cookieDir . '/index.php', 'w+'); @fclose($file_index); } $ch = curl_init(); if ($website != null) { $cookieFile = $cookieDir . '/' . sha1(sha1('mainwp' . LOGGED_IN_SALT . $website->id) . NONCE_SALT . 'WP_Cookie'); if (!file_exists($cookieFile)) { @file_put_contents($cookieFile, ''); } if (file_exists($cookieFile)) { @curl_setopt($ch, CURLOPT_COOKIEJAR, $cookieFile); @curl_setopt($ch, CURLOPT_COOKIEFILE, $cookieFile); } } @curl_setopt($ch, CURLOPT_URL, $url); @curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); @curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); @curl_setopt($ch, CURLOPT_POST, true); @curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata); @curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10); @curl_setopt($ch, CURLOPT_USERAGENT, $agent); if (!empty($http_user) && !empty($http_pass)) { @curl_setopt($ch, CURLOPT_USERPWD, "{$http_user}:{$http_pass}"); } $ssl_verifyhost = false; if ($verifyCertificate !== null) { if ($verifyCertificate == 1) { $ssl_verifyhost = true; } else { if ($verifyCertificate == 2) { // use global setting if (get_option('mainwp_sslVerifyCertificate') === false || get_option('mainwp_sslVerifyCertificate') == 1) { $ssl_verifyhost = true; } } } } else { if (get_option('mainwp_sslVerifyCertificate') === false || get_option('mainwp_sslVerifyCertificate') == 1) { $ssl_verifyhost = true; } } if ($ssl_verifyhost) { @curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2); @curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true); } else { @curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); @curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); } $timeout = 20 * 60 * 60; //20 minutes @curl_setopt($ch, CURLOPT_TIMEOUT, $timeout); if (!ini_get('safe_mode')) { @set_time_limit($timeout); } @ini_set('max_execution_time', $timeout); MainWPUtility::endSession(); $disabled_functions = ini_get('disable_functions'); if (empty($disabled_functions) || stristr($disabled_functions, 'curl_multi_exec') === false) { $mh = @curl_multi_init(); @curl_multi_add_handle($mh, $ch); $lastRun = 0; do { if (time() - $lastRun > 20) { @set_time_limit($timeout); //reset timer.. $lastRun = time(); } @curl_multi_exec($mh, $running); //Execute handlers //$ready = curl_multi_select($mh); while ($info = @curl_multi_info_read($mh)) { $data = @curl_multi_getcontent($info['handle']); $http_status = @curl_getinfo($info['handle'], CURLINFO_HTTP_CODE); $err = @curl_error($info['handle']); $real_url = @curl_getinfo($info['handle'], CURLINFO_EFFECTIVE_URL); @curl_multi_remove_handle($mh, $info['handle']); } usleep(10000); } while ($running > 0); @curl_multi_close($mh); } else { $data = @curl_exec($ch); $http_status = @curl_getinfo($ch, CURLINFO_HTTP_CODE); $err = @curl_error($ch); $real_url = @curl_getinfo($ch, CURLINFO_EFFECTIVE_URL); } $host = parse_url($real_url, PHP_URL_HOST); $ip = gethostbyname($host); if ($website != null) { MainWPDB::Instance()->insertOrUpdateRequestLog($website->id, $ip, null, microtime(true)); } if ($data === false && $http_status == 0) { MainWPLogger::Instance()->debugForWebsite($website, 'fetchUrl', '[' . $url . '] HTTP Error: [status=0][' . $err . ']'); throw new MainWPException('HTTPERROR', $err); } else { if (empty($data) && !empty($err)) { MainWPLogger::Instance()->debugForWebsite($website, 'fetchUrl', '[' . $url . '] HTTP Error: [status=' . $http_status . '][' . $err . ']'); throw new MainWPException('HTTPERROR', $err); } else { if (preg_match('/<mainwp>(.*)<\\/mainwp>/', $data, $results) > 0) { $result = $results[1]; $information = unserialize(base64_decode($result)); return $information; } else { MainWPLogger::Instance()->debugForWebsite($website, 'fetchUrl', '[' . $url . '] Result was: [' . $data . ']'); throw new MainWPException('NOMAINWP', $url); } } } }
public static function syncSite(&$pWebsite = null, $pForceFetch = false, $pAllowDisconnect = true) { if ($pWebsite == null) { return false; } $userExtension = MainWPDB::Instance()->getUserExtensionByUserId($pWebsite->userid); if ($userExtension == null) { return false; } MainWPUtility::endSession(); try { $pluginDir = $pWebsite->pluginDir; if ($pluginDir == '') { $pluginDir = $userExtension->pluginDir; } $cloneEnabled = apply_filters('mainwp_clone_enabled', false); $cloneSites = array(); if ($cloneEnabled) { $disallowedCloneSites = get_option('mainwp_clone_disallowedsites'); if ($disallowedCloneSites === false) { $disallowedCloneSites = array(); } $websites = MainWPDB::Instance()->query(MainWPDB::Instance()->getSQLWebsitesForCurrentUser()); if ($websites) { while ($websites && ($website = @MainWPDB::fetch_object($websites))) { if (in_array($website->id, $disallowedCloneSites)) { continue; } if ($website->id == $pWebsite->id) { continue; } $cloneSites[$website->id] = array('name' => $website->name, 'url' => $website->url, 'extauth' => $website->extauth, 'size' => $website->totalsize); } @MainWPDB::free_result($websites); } } $pluginConflicts = get_option('mainwp_pluginConflicts'); if ($pluginConflicts !== false) { $pluginConflicts = array_keys($pluginConflicts); } $themeConflicts = get_option('mainwp_themeConflicts'); if ($themeConflicts !== false) { $themeConflicts = array_keys($themeConflicts); } $othersData = apply_filters('mainwp-sync-others-data', array(), $pWebsite); $information = MainWPUtility::fetchUrlAuthed($pWebsite, 'stats', array('optimize' => get_option("mainwp_optimize") == 1 ? 1 : 0, 'heatMap' => MainWPExtensions::isExtensionAvailable('mainwp-heatmap-extension') ? $userExtension->heatMap : 0, 'pluginDir' => $pluginDir, 'cloneSites' => !$cloneEnabled ? 0 : urlencode(json_encode($cloneSites)), 'pluginConflicts' => json_encode($pluginConflicts), 'themeConflicts' => json_encode($themeConflicts), 'othersData' => json_encode($othersData)), true, $pForceFetch); $return = self::syncInformationArray($pWebsite, $information, '', 1, false, $pAllowDisconnect); return $return; } catch (MainWPException $e) { $sync_errors = ''; $offline_check_result = 1; if ($e->getMessage() == 'HTTPERROR') { $sync_errors = __('HTTP error', 'mainwp') . ($e->getMessageExtra() != null ? ' - ' . $e->getMessageExtra() : ''); $offline_check_result = -1; } else { if ($e->getMessage() == 'NOMAINWP') { $sync_errors = __('MainWP not detected', 'mainwp'); $offline_check_result = 1; } } return self::syncInformationArray($pWebsite, $information, $sync_errors, $offline_check_result, true, $pAllowDisconnect); } }