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 ParentReference(); $parent->setId($parentId); $file->setParents(array($parent)); } try { $data = file_get_contents($filename); $createdFile = $service->files->insert($file, array('data' => $data, '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(); } }
/** * 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; }
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']; }
/** * Copy an existing file. * * @param Google_DriveService $service Drive API service instance. * @param String $originFileId ID of the origin file to copy. * @param String $copyTitle Title of the copy. * @return DriveFile The copied file. NULL is returned if an API error occurred. */ function copyFile($service, $originFileId, $copyTitle, $parentId) { $copiedFile = new Google_DriveFile(); $parent = new Google_ParentReference(); $parent->setId($parentId); $copiedFile->setParents(array($parent)); $copiedFile->setTitle($copyTitle); try { return $service->files->copy($originFileId, $copiedFile); } catch (Exception $e) { print "An error occurred: " . $e->getMessage(); } return NULL; }
public function touch($path, $mtime = null) { $file = $this->getDriveFile($path); $result = false; if ($file) { if (isset($mtime)) { $file->setModifiedDate($mtime); $result = $this->service->files->patch($file->getId(), $file, array('setModifiedDate' => true)); } else { $result = $this->service->files->touch($file->getId()); } } else { $parentFolder = $this->getDriveFile(dirname($path)); if ($parentFolder) { $file = new \Google_DriveFile(); $file->setTitle(basename($path)); $parent = new \Google_ParentReference(); $parent->setId($parentFolder->getId()); $file->setParents(array($parent)); $result = $this->service->files->insert($file); } } if ($result) { $this->setDriveFile($path, $result); } return (bool) $result; }
public function createFolder($title, $parentId = null) { $client = $this->getClient(); $service = new Google_DriveService($client); $file = new Google_DriveFile(); $file->setTitle($title); $file->setMimeType('application/vnd.google-apps.folder'); if (null !== $parentId) { $parent = new Google_ParentReference(); $parent->setId($parentId); $file->setParents(array($parent)); } return $service->files->insert($file, array('mimeType' => 'application/vnd.google-apps.folder')); }
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); } } }
function uploadFile($filePath = "", $fileName, $folderId = null) { if ($fileName == null) { $fileName = basename($filePath); } $data = ""; $file = new Google_DriveFile(); $file->setTitle($fileName); if ($filePath) { $file->setMimeType(''); $data = file_get_contents($filePath); } else { $file->setMimeType('application/vnd.google-apps.folder'); } if ($folderId != null) { $folders = explode(",", $folderId); $parents = array(); foreach ($folders as $folder) { $parent = new Google_ParentReference(); $parent->setId($folder); array_push($parents, $parent); } $file->setParents($parents); } $service = new Google_DriveService($this->gClient); $createdFile = $service->files->insert($file, array('data' => $data, 'mimeType' => '')); return $createdFile; }
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; } }
public function file_upload($drive, $path) { try { // Check file existence if (file_exists($path)) { $path_parts = pathinfo($path); if (extension_loaded('fileinfo')) { $finfo = finfo_open(); $fileinfo = finfo_file($finfo, $path, FILEINFO_MIME); finfo_close($finfo); } else { $fileinfo = 'application/x-rar-compressed'; } $file = new Google_DriveFile(); $file->setMimeType($fileinfo); $file->setTitle($path_parts['basename']); if ($location = Phpfox::getService('backuprestore.backuprestore')->getBTDBSettingByName('backup_setting')) { $setting_value = unserialize($location['setting_value']); if ($setting_value['sv_subfolder']) { $root = $setting_value['sv_subfolder']; } } else { $root = ''; } if ($fileid = $this->createFolder($drive, $root)) { $parentId = $fileid; } // // Set the parent folder. if ($parentId != null) { $parent = new Google_ParentReference(); $parent->setId($parentId); $file->setParents(array($parent)); } //file_get_contents — Читает содержимое файла в строку $data = file_get_contents($path); } $createdFile = $drive->files->insert($file, array('data' => $data, 'mimeType' => $fileinfo)); return $createdFile->id; } catch (Exception $e) { } throw $e; }
public function putFileChunk($name, $file) { $file = realpath($file); if (!file_exists($file)) { $this->_throwExeption($this->_helper->__('File "%s" doesn\'t exist', strval($file))); } $handle = fopen($file, "rb"); $filename = basename($name); $chunkSize = $this->getChunkSize(); $fileObject = new Google_DriveFile(); $fileObject->setTitle($filename); if (!($mimeType = $this->getRequestMimeType())) { if (substr(".tar.gz", -7)) { $mimeType = self::MIME_TYPE_TGZ; } else { if (substr(".gz", -3)) { $mimeType = self::MIME_TYPE_GZIP; } else { $mimeType = self::MIME_TYPE_GOOGLE_FILES; } } $this->setRequestMimeType($mimeType); } if (!($parentId = $this->getRequestParentId())) { $parentId = $this->getBackupFolder(); $this->setRequestParentId($parentId); } if ($parentId != null) { $parent = new Google_ParentReference(); $parent->setId($parentId); $fileObject->setParents(array($parent)); } $media = new Google_MediaFileUpload($mimeType, null, true, $chunkSize); if (!($fileSize = $this->getRequestFileSize())) { $fileSize = $this->filesize($file); } $media->setFileSize($fileSize); $byte = $startByte = (double) $this->getRequestBytes(); if ($byte > 0) { $this->fseek($handle, $byte); $media->resumeUri = $this->getRequestUrl(); $media->progress = $byte; } /** * @var Google_HttpRequest $httpRequest * @see Google_FilesServiceResource::insert */ $httpRequest = $this->getService(false)->files->insert($fileObject, array('mimeType' => $mimeType, 'mediaUpload' => $media)); while (!feof($handle)) { if ($this->timeIsUp()) { $this->setRequestBytes($byte); $this->setRequestUrl($media->resumeUri); $nextChunk = true; break; } $chunk = fread($handle, $chunkSize); $uploadStatus = $media->nextChunk($httpRequest, $chunk); $byte += $chunkSize; } fclose($handle); $locale = Mage::app()->getLocale()->getLocale(); if (isset($nextChunk)) { $this->_addBackupProcessMessage($this->_helper->__('Bytes from %1$s to %2$s were added (total: %3$s)', Zend_Locale_Format::toNumber($startByte, array('precision' => 0, 'locale' => $locale)), Zend_Locale_Format::toNumber($byte, array('precision' => 0, 'locale' => $locale)), Zend_Locale_Format::toNumber($fileSize, array('precision' => 0, 'locale' => $locale)))); return false; } $this->_addBackupProcessMessage($this->_helper->__('Bytes from %1$s to %2$s were added (total: %3$s)', Zend_Locale_Format::toNumber($startByte, array('precision' => 0, 'locale' => $locale)), Zend_Locale_Format::toNumber($fileSize, array('precision' => 0, 'locale' => $locale)), Zend_Locale_Format::toNumber($fileSize, array('precision' => 0, 'locale' => $locale)))); if (!isset($uploadStatus) || !is_array($uploadStatus) || empty($uploadStatus['id'])) { $this->_throwExeption($this->_helper->__('Error chunk upload response')); } $fileCloudPath = $this->getConfigValue(self::APP_PATH); $returnPath = $fileCloudPath . '/' . $filename; $this->_addAdditionalInfo($uploadStatus['id'], $returnPath); $this->clearRequestParams(); return $returnPath; }