Example #1
0
function mwp_format_memory_limit($limit)
{
    if ((string) (int) $limit === (string) $limit) {
        // The number is numeric.
        return mwp_format_bytes($limit);
    }
    $units = strtolower(substr($limit, -1));
    if (!in_array($units, array('b', 'k', 'm', 'g'))) {
        // Invalid size unit.
        return $limit;
    }
    $number = substr($limit, 0, -1);
    if ((string) (int) $number !== $number) {
        // The number isn't numeric.
        return $number;
    }
    switch ($units) {
        case 'g':
            return $number . ' GB';
        case 'm':
            return $number . ' MB';
        case 'k':
            return $number . ' KB';
        case 'b':
        default:
            return $number . ' B';
    }
}
Example #2
0
 /**
  * Downloads backup file from Google Drive to root folder on local server.
  *
  * @param array $args arguments passed to the function
  *                    [google_drive_token] -> user's Google drive token in json form
  *                    [google_drive_directory] -> folder on user's Google Drive account which backup file should be downloaded from
  *                    [google_drive_site_folder] -> subfolder with site name in google_drive_directory which backup file should be downloaded from
  *                    [backup_file] -> absolute path of backup file on local server
  *                    [file_id] -> google file id
  *
  * @return bool|array absolute path to downloaded file is successful, array with error message if not
  */
 public function get_google_drive_backup($args)
 {
     mwp_register_autoload_google();
     $googleClient = new Google_ApiClient();
     $googleClient->setAccessToken($args['google_drive_token']);
     $driveService = new Google_Service_Drive($googleClient);
     mwp_logger()->info('Connecting to Google Drive');
     try {
         $about = $driveService->about->get();
         $rootFolderId = $about->getRootFolderId();
     } catch (Exception $e) {
         mwp_logger()->error('Error while connecting to Google Drive', array('exception' => $e));
         return array('error' => 'Error while connecting to Google Drive: ' . $e->getMessage());
     }
     if (empty($args['file_id'])) {
         mwp_logger()->info('Looking for backup directory');
         try {
             $backupFolderFiles = $driveService->files->listFiles(array('q' => sprintf("title='%s' and '%s' in parents and trashed = false", addslashes($args['google_drive_directory']), $rootFolderId)));
         } catch (Exception $e) {
             mwp_logger()->error('Error while looking for backup directory', array('exception' => $e));
             return array('error' => 'Error while looking for backup directory: ' . $e->getMessage());
         }
         if (!$backupFolderFiles->offsetExists(0)) {
             mwp_logger()->error('Backup directory ("{directory}") does not exist', array('directory' => $args['google_drive_directory']));
             return array('error' => sprintf("The backup directory (%s) does not exist.", $args['google_drive_directory']));
         }
         /** @var Google_Service_Drive_DriveFile $backupFolder */
         $backupFolder = $backupFolderFiles->offsetGet(0);
         if ($args['google_drive_site_folder']) {
             mwp_logger()->info('Looking into the site folder');
             try {
                 $siteFolderFiles = $driveService->files->listFiles(array('q' => sprintf("title='%s' and '%s' in parents and trashed = false", addslashes($this->site_name), $backupFolder->getId())));
             } catch (Exception $e) {
                 mwp_logger()->error('Error while looking for the site folder', array('exception' => $e));
                 return array('error' => 'Error while looking for the site folder: ' . $e->getMessage());
             }
             if ($siteFolderFiles->offsetExists(0)) {
                 $backupFolder = $siteFolderFiles->offsetGet(0);
             }
         }
         try {
             $backupFiles = $driveService->files->listFiles(array('q' => sprintf("title='%s' and '%s' in parents and trashed = false", addslashes($args['backup_file']), $backupFolder->getId())));
         } catch (Exception $e) {
             mwp_logger()->error('Error while fetching Google Drive backup file', array('file_name' => $args['backup_file'], 'exception' => $e));
             return array('error' => 'Error while fetching Google Drive backup file: ' . $e->getMessage());
         }
         if (!$backupFiles->offsetExists(0)) {
             return array('error' => sprintf('Backup file "%s" was not found on your Google Drive account.', $args['backup_file']));
         }
         /** @var Google_Service_Drive_DriveFile $backupFile */
         $backupFile = $backupFiles->offsetGet(0);
     } else {
         try {
             /** @var Google_Service_Drive_DriveFile $backupFile */
             $backupFile = $driveService->files->get($args['file_id']);
         } catch (Exception $e) {
             mwp_logger()->error('Error while fetching Google Drive backup file by id', array('file_id' => $args['file_id'], 'exception' => $e));
             return array('error' => 'Error while fetching Google Drive backup file: ' . $e->getMessage());
         }
     }
     $downloadUrl = $backupFile->getDownloadUrl();
     $downloadLocation = ABSPATH . 'mwp_temp_backup.zip';
     $fileSize = $backupFile->getFileSize();
     $downloaded = 0;
     $chunkSize = 1024 * 1024 * 4;
     $fh = fopen($downloadLocation, 'w+');
     if (!is_resource($fh)) {
         return array('error' => 'Temporary backup download location is not writable (location: "%s").', $downloadLocation);
     }
     while ($downloaded < $fileSize) {
         $request = new Google_Http_Request($downloadUrl);
         $googleClient->getAuth()->sign($request);
         $toDownload = min($chunkSize, $fileSize - $downloaded);
         mwp_logger()->info('Downloading: {downloaded}/{size}', array('downloaded' => mwp_format_bytes($downloaded), 'size' => mwp_format_bytes($fileSize)));
         $request->setRequestHeaders($request->getRequestHeaders() + array('Range' => 'bytes=' . $downloaded . '-' . ($downloaded + $toDownload - 1)));
         $googleClient->getIo()->makeRequest($request);
         if ($request->getResponseHttpCode() !== 206) {
             mwp_logger()->error('Google Drive has returned an invalid response', array('response_headers' => $request->getResponseHeaders(), 'response_body' => $request->getResponseBody()));
             return array('error' => sprintf('Google Drive service has returned an invalid response code (%s)', $request->getResponseHttpCode()));
         }
         fwrite($fh, $request->getResponseBody());
         $downloaded += $toDownload;
     }
     fclose($fh);
     $fileMd5 = md5_file($downloadLocation);
     if ($backupFile->getMd5Checksum() !== $fileMd5) {
         mwp_logger()->error('File checksum does not match, downloaded file is corrupted.', array('original' => $backupFile->getMd5Checksum(), 'downloaded' => $fileMd5));
         return array('error' => 'File downloaded was corrupted.');
     }
     return $downloadLocation;
 }