/** * Uploads backup file from server to Google Drive. * * @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 upload to * [google_drive_site_folder] -> subfolder with site name in google_drive_directory which backup file should be upload to * [backup_file] -> absolute path of backup file on local server * @return bool|array true is successful, array with error message if not */ function google_drive_backup($args) { extract($args); global $mmb_plugin_dir; require_once "{$mmb_plugin_dir}/lib/google-api-client/Google_Client.php"; require_once "{$mmb_plugin_dir}/lib/google-api-client/contrib/Google_DriveService.php"; $gdrive_client = new Google_Client(); $gdrive_client->setUseObjects(true); $gdrive_client->setAccessToken($google_drive_token); $gdrive_service = new Google_DriveService($gdrive_client); try { $about = $gdrive_service->about->get(); $root_folder_id = $about->getRootFolderId(); } catch (Exception $e) { return array('error' => $e->getMessage()); } try { $list_files = $gdrive_service->files->listFiles(array("q" => "title='{$google_drive_directory}' and '{$root_folder_id}' in parents and trashed = false")); $files = $list_files->getItems(); } catch (Exception $e) { return array('error' => $e->getMessage()); } if (isset($files[0])) { $managewp_folder = $files[0]; } if (!isset($managewp_folder)) { try { $_managewp_folder = new Google_DriveFile(); $_managewp_folder->setTitle($google_drive_directory); $_managewp_folder->setMimeType('application/vnd.google-apps.folder'); if ($root_folder_id != null) { $parent = new Google_ParentReference(); $parent->setId($root_folder_id); $_managewp_folder->setParents(array($parent)); } $managewp_folder = $gdrive_service->files->insert($_managewp_folder, array()); } catch (Exception $e) { return array('error' => $e->getMessage()); } } if ($google_drive_site_folder) { try { $subfolder_title = $this->site_name; $managewp_folder_id = $managewp_folder->getId(); $list_files = $gdrive_service->files->listFiles(array("q" => "title='{$subfolder_title}' and '{$managewp_folder_id}' in parents and trashed = false")); $files = $list_files->getItems(); } catch (Exception $e) { return array('error' => $e->getMessage()); } if (isset($files[0])) { $backup_folder = $files[0]; } else { try { $_backup_folder = new Google_DriveFile(); $_backup_folder->setTitle($subfolder_title); $_backup_folder->setMimeType('application/vnd.google-apps.folder'); if (isset($managewp_folder)) { $_backup_folder->setParents(array($managewp_folder)); } $backup_folder = $gdrive_service->files->insert($_backup_folder, array()); } catch (Exception $e) { return array('error' => $e->getMessage()); } } } else { $backup_folder = $managewp_folder; } $file_path = explode('/', $backup_file); $new_file = new Google_DriveFile(); $new_file->setTitle(end($file_path)); $new_file->setDescription('Backup file of site: ' . $this->site_name . '.'); if ($backup_folder != null) { $new_file->setParents(array($backup_folder)); } $tries = 1; while ($tries <= 2) { try { $data = file_get_contents($backup_file); $createdFile = $gdrive_service->files->insert($new_file, array('data' => $data)); break; } catch (Exception $e) { if ($e->getCode() >= 500 && $e->getCode() <= 504 && $mmb_gdrive_upload_tries <= 2) { sleep(2); $tries++; } else { return array('error' => $e->getMessage()); } } } return true; }
/** * Run the backup */ public function backup($files) { $fail = false; $this->_client->setAccessToken($this->_plugin->setting(self::token_setting)); foreach ($files as $src => $filename) { $file = new \Google_DriveFile(); $file->setTitle($filename); $file->setDescription('GetSimple site backup'); $data = file_get_contents($src); try { $created_file = $this->_service->files->insert($file, array('data' => $data)); } catch (Exception $e) { die($e->getMessage()); break; } } return !$fail; }
require_once 'google-api-php-client/src/Google_Client.php'; require_once 'google-api-php-client/src/contrib/Google_DriveService.php'; require_once 'google-api-php-client/src/contrib/Google_Oauth2Service.php'; $client = new Google_Client(); // Get your credentials from the console $client->setClientId('1076903159369-5nv7tblb6nnlks5qbl588qhhoff894r0.apps.googleusercontent.com'); $client->setClientSecret('oRCdkRIqRQ53SlTyKIelJLMV'); $client->setRedirectUri(''); $client->setScopes(array('https://www.googleapis.com/auth/drive')); $service = new Google_DriveService($client); $authUrl = $client->createAuthUrl(); if (isset($_GET['code'])) { $authCode = trim($_GET['code']); // Exchange authorization code for access token $accessToken = $client->authenticate($authCode); $client->setAccessToken($accessToken); //Insert a file $file = new Google_DriveFile(); $file->setTitle('My document - ' . date('m-d-Y', time())); $file->setDescription('A test document'); $file->setMimeType('text/plain'); $data = file_get_contents('backupdb.sql'); $createdFile = $service->files->insert($file, array('data' => $data, 'mimeType' => 'text/plain')); if ($createdFile) { echo "<script>alert('Database exported into Google Drive successfully');</script>"; } else { echo "<script>alert('Error! while uploading file');</script>"; } } else { echo "<script>window.location.href='" . $authUrl . "';</script>"; }
public function createFile($name, $mime, $description, $content, Google_ParentReference $fileParent = null) { $file = new Google_DriveFile(); $file->setTitle($name); $file->setDescription($description); $file->setMimeType($mime); if ($fileParent) { $file->setParents(array($fileParent)); } $createdFile = $this->_service->files->insert($file, array('data' => $content, 'mimeType' => $mime)); return $createdFile['id']; }
public static function wp_db_backup_completed(&$args) { $authCode = get_option('wpdb_dest_google_authCode'); $clientId = get_option('wpdb_dest_google_client_key'); $clientSecret = get_option('wpdb_dest_google_secret_key'); if (!empty($authCode) && !empty($clientId) && !empty($clientSecret)) { set_time_limit(0); require_once "google-api-php-client/src/Google_Client.php"; require_once "google-api-php-client/src/contrib/Google_DriveService.php"; $client = new Google_Client(); // Get your credentials from the APIs Console $client->setClientId($clientId); $client->setClientSecret($clientSecret); $client->setRedirectUri(site_url() . '/wp-admin/tools.php?page=wp-database-backup&action=auth'); $client->setScopes(array("https://www.googleapis.com/auth/drive")); $service = new Google_DriveService($client); // Exchange authorisation code for access token if (!file_exists("token.json")) { // Save token for future use $accessToken = $client->authenticate($authCode); file_put_contents("token.json", $accessToken); } else { $accessToken = file_get_contents("token.json"); } $client->setAccessToken($accessToken); // Upload file to Google Drive $file = new Google_DriveFile(); $file->setTitle($args[0]); $file->setDescription("WP Database Backup : database backup file-" . site_url()); $file->setMimeType("application/gzip"); $data = file_get_contents($args[1]); $createdFile = $service->files->insert($file, array('data' => $data, 'mimeType' => "application/gzip")); $args[2] = $args[2] . '<br> Upload Database Backup on google drive'; // Process response here.... } }
/** * Insert new file. * * @param Google_DriveService $service Drive API service instance. * @param string $title Title of the file to insert, including the extension. * @param string $description Description of the file to insert. * @param string $parentId Parent folder's ID. * @param string $mimeType MIME type of the file to insert. * @param string $filename Filename of the file to insert. * @return Google_DriveFile The file that was inserted. NULL is returned if an API error occurred. */ function insertFile($service, $title, $description, $parentId, $mimeType, $filename) { $file = new Google_DriveFile(); $file->setTitle($title); $file->setDescription($description); $file->setMimeType($mimeType); // Set the parent folder. if ($parentId != null) { $parent = new Google_ParentReference(); $parent->setId($parentId); $file->setParents(array($parent)); } try { if ($mimeType != 'application/vnd.google-apps.folder') { $data = file_get_contents($filename); $createdFile = $service->files->insert($file, array('data' => $data, 'mimeType' => $mimeType)); } else { $createdFile = $service->files->insert($file, array('mimeType' => $mimeType)); } // Uncomment the following line to print the File ID // print 'File ID: %s' % $createdFile->getId(); return $createdFile; } catch (Exception $e) { print "An error occurred: " . $e->getMessage(); } }
/** * Upload files to Google Drive * * @since 1.1 * @param array $files * @return integer */ public function upload($files, $stacksFolder = '') { if (is_array($files) === false) { $files = explode(',', $files); } if ($this->isAuthenticated() === false) { return 401; } $client = $this->getClient(); $service = new Google_DriveService($client); $domain = $this->getDomain(basename($stacksFolder)); if (!$domain) { $this->pushError(__('Unable to get parent folder ID.', BUP_LANG_CODE)); return 500; } $parent = new Google_ParentReference(); $parent->setId($domain['id']); foreach ($files as $storageFile) { if (file_exists($filepath = $this->getBackupsPath() . $stacksFolder . basename($storageFile))) { // Ugly hack to prevent log-*.txt upload if (pathinfo($filepath, PATHINFO_EXTENSION) != 'txt') { $file = new Google_DriveFile(); $file->setTitle(basename($storageFile)); $file->setDescription('Backup by Supsystic'); $file->setMimeType($this->getMimetype($filepath)); $file->setParents(array($parent)); $service->files->insert($file, array('data' => file_get_contents($filepath), 'mimeType' => $this->getMimetype($filepath))); } } } return 201; }
public function uploadfile() { if ($_FILES['upld_file'] && $this->input->post('folderid')) { try { $client = $this->google_client; $client->setAccessToken($this->session->userdata('accessToken')); $service = new Google_DriveService($client); $folderdetailArray = $this->usermodel->getallfolders($this->input->post('folderid'), 'getbyId'); //pr($folderdetailArray); /*$file = new Google_DriveFile(); $file->setTitle($_FILES['upld_file']['name']); $file->setDescription('This is a '.$_FILES['upld_file']['type'].' document'); $file->setMimeType($_FILES['upld_file']['type']); $service->files->insert( $file, array( 'data' => file_get_contents($_FILES['upld_file']['tmp_name']), 'mimeType' => $_FILES['upld_file']['type'] ) );*/ $title = $_FILES['upld_file']['name']; $description = 'This is a ' . $_FILES['upld_file']['type'] . ' document'; $parentId = $folderdetailArray[0]['googlefolderId']; $mimeType = $_FILES['upld_file']['type']; $filename = $_FILES['upld_file']['name']; $filepath = $_FILES['upld_file']['tmp_name']; $file = new Google_DriveFile(); $file->setTitle($title); $file->setDescription($description); $file->setMimeType($mimeType); if ($parentId != null) { $parent = new Google_ParentReference(); $parent->setId($parentId); $file->setParents(array($parent)); } $service->files->insert($file, array('data' => file_get_contents($filepath), 'mimeType' => $mimeType)); //pr($service); /*Recent file insert function call*/ $array = array('title' => $title, 'doc_id' => '', 'doc_type' => $mimeType, 'folder_id' => $parentId, 'folder_name' => '', 'user_id' => $this->session->userdata('userid'), 'action_description' => 'File uploading'); $this->usermodel->saverecentfiles($array); //insertFile($service, $title, $description, $parentId, $mimeType, $filename,$filepath); $this->session->set_flashdata('message', '<div class="alert-success">' . $this->lang->line('file_upload_sucesss') . '</div>'); redirect('users/fileListing/' . $parentId); } catch (Exception $e) { pre($e); exit; $this->session->set_flashdata('message', '<div class="alert-error">' . $this->lang->line('file_upload_sucesss') . '</div>'); redirect('users/fileListing/' . $parentId); } } }
public function createFileFromPath($path, $fileName, $description, Google_ParentReference $fileParent = null) { $mimeType = wp_check_filetype($fileName); $file = new Google_DriveFile(); $file->setTitle($fileName); $file->setDescription($description); $file->setMimeType($mimeType['type']); if ($fileParent) { $file->setParents(array($fileParent)); } $gdwpm_opsi_chunk = get_option('gdwpm_opsi_chunk'); $chunks = $gdwpm_opsi_chunk['drive']['chunk']; $max_retries = (int) $gdwpm_opsi_chunk['drive']['retries']; $chunkSize = 1024 * 1024 * (int) $chunks; // 2mb chunk $fileupload = new Google_MediaFileUpload($mimeType['type'], null, true, $chunkSize); $fileupload->setFileSize(filesize($path)); $mkFile = $this->_service->files->insert($file, array('mediaUpload' => $fileupload)); $status = false; $handle = fopen($path, "rb"); while (!$status && !feof($handle)) { $max = false; for ($i = 1; $i <= $max_retries; $i++) { $chunked = fread($handle, $chunkSize); if ($chunked) { $createdFile = $fileupload->nextChunk($mkFile, $chunked); break; } elseif ($i == $max_retries) { $max = true; } } if ($max) { if ($createdFile) { $this->_service->files->trash($createdFile['id']); } $createdFile = false; break; } } fclose($handle); if ($createdFile) { return $createdFile['id']; } else { return false; } }
renderJson($app, $file); } catch (Exception $ex) { renderEx($app, $ex); } }); /** * Creates a new file with the metadata and contents * in the request body. Requires login. */ $app->post('/svc', function () use($app, $client, $service) { checkUserAuthentication($app); $inputFile = json_decode($app->request()->getBody()); try { $file = new Google_DriveFile(); $file->setTitle($inputFile->title); $file->setDescription($inputFile->description); $file->setMimeType($mimeType); // Set the parent folder. if ($inputFile->parentId != null) { $parentsCollectionData = new Google_DriveFileParentsCollection(); $parentsCollectionData->setId($inputFile->parentId); $file->setParentsCollection(array($parentsCollectionData)); } $createdFile = $service->files->insert($file, array('data' => $inputFile->content, 'mimeType' => $mimeType)); renderJson($app, $createdFile->id); } catch (Exception $ex) { renderEx($app, $ex); } }); /** * Modifies an existing file given in the request body and responds
// Save token for future use $accessToken = $client->authenticate($authCode); file_put_contents("token.json", $accessToken); } else { $accessToken = file_get_contents("token.json"); } $client->setAccessToken($accessToken); // Upload file to Google Drive $file = new Google_DriveFile(); $file->setTitle($fprefix . $uid . ".tar.gz"); $file->setDescription("Server backup file"); $file->setMimeType("application/gzip"); $data = file_get_contents($homedir . $fprefix . $uid . ".tar.gz"); $createdFile = $service->files->insert($file, array('data' => $data, 'mimeType' => "application/gzip")); // Process response here.... print_r($createdFile); // Upload database to Google Drive $file = new Google_DriveFile(); $file->setTitle($dprefix . $uid . ".sql.gz"); $file->setDescription("Database backup file"); $file->setMimeType("application/gzip"); $data = file_get_contents($homedir . $dprefix . $uid . ".sql.gz"); $createdFile = $service->files->insert($file, array('data' => $data, 'mimeType' => "application/gzip")); // Process response here.... print_r($createdFile); /* CLEANUP */ // Delete created files unlink($homedir . $fprefix . $uid . ".tar.gz"); unlink($homedir . $dprefix . $uid . ".sql.gz"); /* References: https://developers.google.com/drive/quickstart-php */
/** * Upload a file. */ public function actionUpload() { if (isset($_FILES['upload'])) { if (isset($_POST['drive']) && $_POST['drive']) { // google drive $auth = new GoogleAuthenticator(); if ($auth->getAccessToken()) { $service = $auth->getDriveService(); } $createdFile = null; if (isset($service, $_SESSION['access_token'], $_FILES['upload'])) { try { $file = new Google_DriveFile(); $file->setTitle($_FILES['upload']['name']); $file->setDescription('Uploaded by X2Engine'); $file->setMimeType($_FILES['upload']['type']); if (empty($_FILES['upload']['tmp_name'])) { $err = false; switch ($_FILES['newfile']['error']) { case UPLOAD_ERR_INI_SIZE: case UPLOAD_ERR_FORM_SIZE: $err .= 'File size exceeds limit of ' . get_max_upload() . ' bytes.'; break; case UPLOAD_ERR_PARTIAL: $err .= 'File upload was not completed.'; break; case UPLOAD_ERR_NO_FILE: $err .= 'Zero-length file uploaded.'; break; default: $err .= 'Internal error ' . $_FILES['newfile']['error']; break; } if ((bool) $message) { throw new CException($message); } } $data = file_get_contents($_FILES['upload']['tmp_name']); $createdFile = $service->files->insert($file, array('data' => $data, 'mimeType' => $_FILES['upload']['type'])); if (is_array($createdFile)) { $model = new Media(); $model->fileName = $createdFile['id']; $model->name = $createdFile['title']; if (isset($_POST['associationId'])) { $model->associationId = $_POST['associationId']; } if (isset($_POST['associationType'])) { $model->associationType = $_POST['associationType']; } if (isset($_POST['private'])) { $model->private = $_POST['private']; } $model->uploadedBy = Yii::app()->user->getName(); $model->mimetype = $createdFile['mimeType']; $model->filesize = $createdFile['fileSize']; $model->drive = 1; $model->save(); if ($model->associationType == 'feed') { $event = new Events(); $event->user = Yii::app()->user->getName(); if (isset($_POST['attachmentText']) && !empty($_POST['attachmentText'])) { $event->text = $_POST['attachmentText']; } else { $event->text = Yii::t('app', 'Attached file: '); } $event->type = 'media'; $event->timestamp = time(); $event->lastUpdated = time(); $event->associationId = $model->id; $event->associationType = 'Media'; $event->save(); $this->redirect(array('/profile/view', 'id' => Yii::app()->user->getId())); } elseif ($model->associationType == 'docs') { $this->redirect(array('/docs/docs/index')); } elseif (!empty($model->associationType) && !empty($model->associationId)) { $note = new Actions(); $note->createDate = time(); $note->dueDate = time(); $note->completeDate = time(); $note->complete = 'Yes'; $note->visibility = '1'; $note->completedBy = Yii::app()->user->getName(); if ($model->private) { $note->assignedTo = Yii::app()->user->getName(); $note->visibility = '0'; } else { $note->assignedTo = 'Anyone'; } $note->type = 'attachment'; $note->associationId = $_POST['associationId']; $note->associationType = $_POST['associationType']; $association = $this->getAssociation($note->associationType, $note->associationId); if ($association != null) { $note->associationName = $association->name; } $note->actionDescription = $model->fileName . ':' . $model->id; if ($note->save()) { $this->redirect(array($model->associationType . '/' . $model->associationId)); } } else { $this->redirect('/media/media/view', array('id' => $model->id)); } } else { throw new CHttpException('400', 'Invalid request.'); } } catch (Google_AuthException $e) { $auth->flushCredentials(); $auth->setErrors($e->getMessage()); $service = null; $createdFile = null; } } else { if (isset($_SERVER['HTTP_REFERER'])) { $this->redirect($_SERVER['HTTP_REFERER']); } else { throw new CHttpException('400', 'Invalid request'); } } } else { // non-google drive upload $model = new Media(); $temp = CUploadedFile::getInstanceByName('upload'); // file uploaded through form $tempName = $temp->getTempName(); if (isset($temp) && !empty($tempName)) { $name = $temp->getName(); $name = str_replace(' ', '_', $name); $check = Media::model()->findAllByAttributes(array('fileName' => $name)); // rename file if there name conflicts by suffixing "(n)" if (count($check) != 0) { $count = 1; $newName = $name; $arr = explode('.', $name); $name = $arr[0]; while (count($check) != 0) { $newName = $name . '(' . $count . ').' . $temp->getExtensionName(); $check = Media::model()->findAllByAttributes(array('fileName' => $newName)); $count++; } $name = $newName; } $username = Yii::app()->user->name; // copy file to user's media uploads directory if (FileUtil::ccopy($tempName, "uploads/media/{$username}/{$name}")) { if (isset($_POST['associationId'])) { $model->associationId = $_POST['associationId']; } if (isset($_POST['associationType'])) { $model->associationType = $_POST['associationType']; } if (isset($_POST['private'])) { $model->private = $_POST['private']; } $model->uploadedBy = Yii::app()->user->getName(); $model->createDate = time(); $model->lastUpdated = time(); $model->fileName = $name; if (!$model->save()) { $errors = $model->getErrors(); $error = ArrayUtil::pop(ArrayUtil::pop($errors)); Yii::app()->user->setFlash('top-error', Yii::t('app', 'Attachment failed. ' . $error)); $this->redirect(array($model->associationType . '/' . $model->associationType . '/view', 'id' => $model->associationId)); Yii::app()->end(); } // handle different upload types switch ($model->associationType) { case 'feed': $this->handleFeedTypeUpload($model, $name); break; case 'docs': $this->redirect(array('/docs/docs/index')); break; case 'loginSound': case 'notificationSound': $this->redirect(array('/profile/settings', 'id' => Yii::app()->user->getId())); break; case 'bg': case 'bg-private': $this->redirect(array('/profile/settings', 'id' => Yii::app()->user->getId(), 'bgId' => $model->id)); break; default: $this->handleDefaultUpload($model, $name); break; } } } else { if (isset($_SERVER['HTTP_REFERER'])) { $this->redirect($_SERVER['HTTP_REFERER']); } else { throw new CHttpException('400', 'Invalid request'); } } } } else { throw new CHttpException('400', 'Invalid request.'); } }
header('location:' . $url); exit; } elseif (!isset($_SESSION['accessToken'])) { $client->authenticate(); } $files = array(); $dir = dir('files'); while ($file = $dir->read()) { if ($file != '.' && $file != '..') { $files[] = $file; } } $dir->close(); if (!empty($_POST)) { $client->setAccessToken($_SESSION['accessToken']); $service = new Google_DriveService($client); $finfo = finfo_open(FILEINFO_MIME_TYPE); $file = new Google_DriveFile(); foreach ($files as $file_name) { $file_path = 'files/' . $file_name; $mime_type = finfo_file($finfo, $file_path); $file->setTitle($file_name); $file->setDescription('This is a ' . $mime_type . ' document'); $file->setMimeType($mime_type); $service->files->insert($file, array('data' => file_get_contents($file_path), 'mimeType' => $mime_type)); } finfo_close($finfo); header('location:' . $url); exit; } include 'index.phtml';