/** * Creates a file to drive * @param */ public static function createFile($title, $ownerEmail, $sourceDoc = null, $service = null) { if (!$service) { $service = static::getService(); } $title = $title ?: time() . '.doc'; $mime = 'application/vnd.oasis.opendocument.text'; $data = ''; if ($sourceDoc && file_exists($sourceDoc)) { $finfo = finfo_open(FILEINFO_MIME_TYPE); $mime = finfo_file($finfo, $sourceDoc); $data = file_get_contents($sourceDoc); } $file = new Google_Service_Drive_DriveFile(); $file->setMimeType($mime); $file->setTitle($title); // try { $createdFile = $service->files->insert($file, array('data' => $data, 'mimeType' => $mime, 'convert' => true, 'uploadType' => 'media')); $fileId = $createdFile->getId(); $ownerPermission = new Google_Service_Drive_Permission(); $ownerPermission->setValue($ownerEmail); $ownerPermission->setType('user'); $ownerPermission->setRole('writer'); try { $service->permissions->insert($fileId, $ownerPermission, ['emailMessage' => 'You add a file to ' . static::$applicationName . ': ' . $title]); $publicPermission = new Google_Service_Drive_Permission(); $publicPermission->setValue(null); $publicPermission->setType('anyone'); $publicPermission->setRole('reader'); try { $service->permissions->insert($fileId, $publicPermission); return $createdFile->alternateLink; } catch (Exception $e) { throw new HttpServerErrorException(); } } catch (Exception $e) { throw new HttpServerErrorException(); } return $createdFile; // } catch (Exception $e) { // throw new HttpServerErrorException; // } return ''; }
function uploadFile($service, $filePath, $fileName, $mimeType, $destinationFolder) { $file = new Google_Service_Drive_DriveFile(); $file->setTitle($fileName); $file->setDescription($fileName); $file->setMimeType($fileName); $parent = new Google_Service_Drive_ParentReference(); $parent->setId(getParentDirectoryId($service, $destinationFolder)); $file->setParents(array($parent)); try { $data = file_get_contents($filePath . "/" . $fileName); $response = $service->files->insert($file, array('data' => $data, 'mimeType' => $mimeType, 'uploadType' => 'multipart')); return $response; } catch (Exception $e) { throw new Exception("Error: " . $e->getMessage()); } }
<?php 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 console $client->setClientId('135842521742-1fr3rf2q936v5irhqojdgj88s425a17m.apps.googleusercontent.com'); //id-клиента $client->setClientSecret('oklWXEK77tpFdGDiIF-nin48'); //пароль клиента $client->setRedirectUri('urn:ietf:wg:oauth:2.0:oob'); $client->setScopes(array('https://www.googleapis.com/auth/drive')); $service = new Google_Service_Drive($client); $authUrl = $client->createAuthUrl(); //Request authorization print "Please visit:\n{$authUrl}\n\n"; print "Please enter the auth code:\n"; $authCode = trim(fgets(STDIN)); // Exchange authorization code for access token $accessToken = $client->authenticate($authCode); $client->setAccessToken($accessToken); //Insert a file $file = new Google_Service_Drive_DriveFile(); $file->setTitle('My document'); $file->setDescription('A test document'); $file->setMimeType('text/plain'); $data = file_get_contents('document.txt'); $createdFile = $service->files->insert($file, array('data' => $data, 'mimeType' => 'text/plain')); print_r($createdFile);
function upload_file($fileTitle) { $file = new Google_Service_Drive_DriveFile(); $file->setTitle('My document'); $file->setDescription('A test document'); $file->setMimeType('text/plain'); $data = file_get_contents('document.txt'); $createdFile = $service->files->insert($file, array('data' => $data, 'mimeType' => 'text/plain')); print_r($createdFile); }
function insertFile($sDir, $oFile, $service, $description, $parentId, $mimeType) { global $client; $sPath = $sDir . '/' . $oFile; $file = new Google_Service_Drive_DriveFile(); $aFile = explode('.', $oFile); //$file->setTitle(@$aFile[0]); $file->setTitle(@$oFile); $file->setDescription($description); $file->setMimeType($mimeType); // Set the parent folder. if ($parentId != null) { $parent = new Google_Service_Drive_ParentReference(); $parent->setId($parentId); $file->setParents(array($parent)); } try { $data = file_get_contents($sPath); $createdFile = $service->files->insert($file, array('data' => $data, 'mimeType' => $mimeType, 'uploadType' => 'multipart')); // Uncomment the following line to print the File ID // print 'File ID: %s' % $createdFile->getId(); return $createdFile->getId(); } catch (Exception $e) { print "An error occurred: " . $e->getMessage(); } }
private function uploadSupplement($supplementFolderId, $tmpfile, $uploaded_name) { $file = new \Google_Service_Drive_DriveFile(); $file->setTitle($uploaded_name); $parent = new \Google_Service_Drive_ParentReference(); $parent->setId($supplementFolderId); $file->setParents(array($parent)); $file = $this->getDriveService()->files->insert($file, array('data' => file_get_contents($tmpfile), 'mimeType' => 'application/pdf', 'uploadType' => 'multipart')); return $file; }
/** * Store a newly created resource in storage. * * @return Response */ public function store(Request $request) { // $cfgGoogle = \Session::get('_ClientGoogle'); if (isset($cfgGoogle)) { $data = $request->all(); if ($data['type_doc'] == 'gdoc') { $service = new \Google_Service_Drive($cfgGoogle); $file = new \Google_Service_Drive_DriveFile(); $file->setTitle($data['name']); $file->setMimeType('application/vnd.google-apps.document'); $file_rst = $service->files->insert($file); $data['id_doc'] = $file_rst->id; $data['alternateLink'] = $file_rst->alternateLink; $data['embedLink'] = $file_rst->embedLink; $rstDoc = new \App\Doc($data); $rstDoc->save(); if ($request->ajax()) { return response()->json(array('status' => true, 'data' => 'successful created doc by Google', 'info' => $data)); } } elseif ($data['type_doc'] == 'gspreadsheets') { $service = new \Google_Service_Drive($cfgGoogle); $file = new \Google_Service_Drive_DriveFile(); $file->setTitle($data['name']); $file->setMimeType('application/vnd.google-apps.spreadsheet'); $file_rst = $service->files->insert($file); $data['id_doc'] = $file_rst->id; $data['alternateLink'] = $file_rst->alternateLink; $data['embedLink'] = $file_rst->embedLink; $rstDoc = new \App\Doc($data); $rstDoc->save(); if ($request->ajax()) { return response()->json(array('status' => true, 'data' => 'successful created doc by Google', 'info' => $data)); } } elseif ($data['type_doc'] == 'gpresentation') { $service = new \Google_Service_Drive($cfgGoogle); $file = new \Google_Service_Drive_DriveFile(); $file->setTitle($data['name']); $file->setMimeType('application/vnd.google-apps.presentation'); $file_rst = $service->files->insert($file); $data['id_doc'] = $file_rst->id; $data['alternateLink'] = $file_rst->alternateLink; $data['embedLink'] = $file_rst->embedLink; $rstDoc = new \App\Doc($data); $rstDoc->save(); if ($request->ajax()) { return response()->json(array('status' => true, 'data' => 'successful created doc by Google', 'info' => $data)); } } } else { if ($request->ajax()) { return response()->json(array('status' => false, 'data' => 'For sync calendar is need login with Google!')); } } }
public function createFile($name, $mime, $description, $content, Google_Service_Drive_ParentReference $fileParent = null) { $file = new Google_Service_Drive_DriveFile(); $file->setTitle("test.txt"); //$name ); $file->setDescription($description); $file->setMimeType($mime); if ($fileParent) { $file->setParents(array($fileParent)); } $createdFile = $this->sef->files->insert($file, array('data' => $content, 'mimeType' => $mime)); return $createdFile['id']; }
/** * Build and returns a Drive service object authorized with the service accounts * that acts on behalf of the given user. * * @param userEmail The email of the user. * @return Google_Service_Drive service object. */ function buildService($userEmail) { $key = file_get_contents(SERVICE_ACCOUNT_PKCS12_FILE_PATH); $auth = new Google_Auth_AssertionCredentials(SERVICE_ACCOUNT_EMAIL, array(DRIVE_SCOPE), $key); $auth->sub = $userEmail; $client = new Google_Client(); $client->setAssertionCredentials($auth); $service = new Google_Service_Drive($client); $file = new Google_Service_Drive_DriveFile(); $file->setTitle("test.txt"); // Provide file name here and path in below $result = $service->files->insert($file, array('data' => file_get_contents("test.txt"), 'mimeType' => 'application/octet-stream', 'uploadType' => 'media')); echo '<pre>'; print_r($result); echo '</pre>'; }
public function send_package() { if (!$this->client) { throw new portfolio_plugin_exception('noauthtoken', 'portfolio_googledocs'); } foreach ($this->exporter->get_tempfiles() as $file) { try { // Create drivefile object and fill it with data. $drivefile = new Google_Service_Drive_DriveFile(); $drivefile->setTitle($file->get_filename()); $drivefile->setMimeType($file->get_mimetype()); $filecontent = $file->get_content(); $createdfile = $this->service->files->insert($drivefile, array('data' => $filecontent, 'mimeType' => $file->get_mimetype(), 'uploadType' => 'multipart')); } catch (Exception $e) { throw new portfolio_plugin_exception('sendfailed', 'portfolio_gdocs', $file->get_filename()); } } return true; }
function doResumableUpload(Google_Client $client) { // Drive service $driveService = new Google_Service_Drive($client); $gs_basepath = 'gs://' . CloudStorageTools::getDefaultGoogleStorageBucketName(); $fileName = UPLOAD_FILENAME; // 82.52MB file $fileToUploadPath = $gs_basepath . "/{$fileName}"; $uploadFilesize = filesize($fileToUploadPath); $options = array('gs' => array('enable_cache' => false, 'acl' => 'public-read')); $ctx = stream_context_create($options); if (($handle = fopen($fileToUploadPath, 'r', false, $ctx)) === false) { throw new Exception('fopen failed.'); } $mimeType = CloudStorageTools::getContentType($handle); // prepare a drive file $file = new Google_Service_Drive_DriveFile(); $file->setTitle($fileName); $file->setMimeType($mimeType); $file->setFileSize($uploadFilesize); // You can also set the parent folder: // @see https://developers.google.com/drive/v2/reference/files/insert $chunkSizeBytes = 256 * 1024 * 4 * 1; // upload in multiples of 256K (1M * n) // Call the API with the media upload, defer so it doesn't immediately return. $client->setDefer(true); $request = $driveService->files->insert($file); // Create a media file upload to represent our upload process. $media = new Google_Http_MediaFileUpload($client, $request, $mimeType, null, true, $chunkSizeBytes); // set the media filesize to the actual filesize. $media->setFileSize($uploadFilesize); // Upload the various chunks. $status will be false until the process is complete. $status = false; while (!$status && !feof($handle)) { $chunk = readChunk($handle, $chunkSizeBytes); $status = $media->nextChunk($chunk); } fclose($handle); // Reset to the client to execute requests immediately in the future. $client->setDefer(false); var_dump($status); }
function insertFile($service, $title, $description, $parentId, $mimeType, $filename) { $file = new Google_Service_Drive_DriveFile(); $file->setTitle($title); $file->setDescription($description); $file->setMimeType($mimeType); // Set the parent folder. if ($parentId != null) { $parent = new Google_Service_Drive_ParentReference(); $parent->setId($parentId); $file->setParents(array($parent)); } try { $data = file_get_contents($filename); $createdFile = $service->files->insert($file, array('data' => $data, 'convert' => true, 'mimeType' => $mimeType, 'uploadType' => 'multipart')); return $createdFile; } catch (Exception $e) { print "An error occurred: " . $e->getMessage(); } }
/** * createFolder * * Erstellt einen neuen Ordner innerhalb des virtuellen Datenspeichers * * @param string $folder Pfad des neuen Ordners inkusive Ordnername innerhalb des virtuellen Datenspeichers */ function createFolder($folder) { if ($folder == "") { return false; } elseif (substr($folder, 0, 1) == "/") { $path = $this->ext_root . $folder; } else { $path = $this->ext_root . "/" . $folder; } $newFolderMetadata = $this->getMetadataByPath($path); $folderMetadata = $this->getMetadataByPath(dirname($path)); //Ordner nur Anlegen wenn übergordneter Ordner exisiert und er selbst noch nicht exisiert if ($folderMetadata && !$newFolderMetadata) { $parentId = $folderMetadata["id"]; $file = new Google_Service_Drive_DriveFile(); $file->setTitle(basename($path)); $parent = new Google_Service_Drive_ParentReference(); $parent->setId($parentId); $file->setParents(array($parent)); $file->setMimetype("application/vnd.google-apps.folder"); return $this->gdrClient->files->insert($file); } return null; }
/** * Checks if a file exists * * @param string $file path to file and filename * @param string $url the live URL to the file * @param bool $is_update perform an update instead of creating a new file * * @since 1.0 * * @return bool */ public function file_upload($file, $url, $is_update = false) { $this->_file_uploaded = false; // get the google drive service if (!isset($this->_google_drive_service)) { $this->_google_drive_service = new Google_Service_Drive($this->_google_drive_cdn->get_google_client()); } // get the google drive service instance $service = $this->_google_drive_service; if (!$service instanceof Google_Service_Drive) { return $url; } // get the folder id $folder_id = WPB_Google_Drive_Cdn_Settings::get_setting('folder_id', 'wpbgdc_folders'); // create the folder name $file_folder_to_str = str_replace(WP_CONTENT_DIR, '', str_replace(basename($file), '', $file)); $file_folder_to_str = str_replace('/', '_', $file_folder_to_str); $file_folder_to_str = sanitize_key($file_folder_to_str); // create the file basename $file_basename = $file_folder_to_str . basename($file); // get the google drive URL $google_drive_url = WPB_Google_Drive_Cdn_Settings::get_setting('folder_link', 'wpbgdc_folders'); try { // search for the file. $files = $service->files->listFiles(array('q' => "title='" . $file_basename . "' and '" . $folder_id . "' in parents")); } catch (Exception $e) { // if there is an error fetching the file, return the normal url return $url; } // checks if the file is a CSS file $is_css_file = substr($file, -4, 4) == '.css'; // search in the list of files for the current file foreach ($files->items as $g_file) { if (!$g_file instanceof Google_Service_Drive_DriveFile) { continue; } // file exists if ($g_file->getTitle() == $file_basename) { // get the date of the current file $file_date = filemtime($file); /** * check if we should update the file * this is the case when either * the date of the file on Google Drive is lower than the local file OR * when the etag is not correct (this is only used for css files at the moment) */ if (strtotime($g_file->getModifiedDate()) < $file_date or $is_css_file && $g_file->getEtag() != $this->get_etag_by_live_url($url)) { $additionalParams = array(); if ($is_css_file) { $additionalParams['data'] = $this->invoke_css_file($file, $url); $additionalParams['mimeType'] = 'text/css'; } else { $additionalParams['data'] = file_get_contents($file); } try { $g_file = $service->files->update($g_file->getId(), $g_file, $additionalParams); } catch (Exception $e) { $this->_google_drive_cdn->set_error($e->getMessage() . '(wpbgdc: file_upload 1; File: ' . $url . ')', false); } $this->_file_uploaded = true; } // update the file cache entry as well $this->set_cached_url($url, $google_drive_url . $g_file->getTitle(), $g_file->getId(), $g_file->getEtag()); // create the URL out of the Drive URL and return it. return $google_drive_url . $g_file->getTitle(); } } if ($is_css_file) { $mime_type = 'text/css'; } else { $mime_type = wp_check_filetype($file); $mime_type = $mime_type['type']; } $parent = new Google_Service_Drive_ParentReference(); $parent->setId($folder_id); // upload the file $new_file = new Google_Service_Drive_DriveFile(); $new_file->setTitle($file_basename); $new_file->setMimeType($mime_type); $new_file->setParents(array($parent)); $new_file->setFileSize(filesize($file)); $additionalParams = array('mimeType' => $mime_type, 'uploadType' => 'media'); if ($is_css_file) { $additionalParams['data'] = $this->invoke_css_file($file, $url); } else { $additionalParams['data'] = file_get_contents($file); } try { $createdFile = $service->files->insert($new_file, $additionalParams); } catch (Exception $e) { $this->_google_drive_cdn->set_error($e->getMessage() . '(wpbgdc: file_upload 2; File: ' . $url . ')', false); return $url; } $file_drive_url = $google_drive_url . $createdFile->getTitle(); $this->set_cached_url($url, $file_drive_url, $createdFile->getId(), $createdFile->getEtag()); $this->_file_uploaded = true; return $file_drive_url; }
/** * Insert new file in the Application Data folder. * * @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 $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, $mimeType, $filename, $folderName, $folderDesc) { $file = new Google_Service_Drive_DriveFile(); $new_mime_type = 'application/vnd.google-apps.document'; // Set the metadata $file->setTitle($title); $file->setDescription($description); $file->setMimeType($new_mime_type); // Setup the folder you want the file in, if it is wanted in a folder if (isset($folderName)) { if (!empty($folderName)) { $parent = new Google_Service_Drive_ParentReference(); $parent->setId(getFolderExistsCreate($service, $folderName, $folderDesc)); $file->setParents(array($parent)); } } try { // Get the contents of the file uploaded $data = file_get_contents($filename); // Try to upload the file, you can add the parameters e.g. if you want to convert a .doc to editable google format, add 'convert' = 'true' $createdFile = $service->files->insert($file, array('data' => $data, 'mimeType' => $mimeType, 'uploadType' => 'multipart', 'convert' => 'true')); // Return a bunch of data including the link to the file we just uploaded return $createdFile; } catch (Exception $e) { print "An error occurred: " . $e->getMessage(); } }
public function id_from_path($path, $retry = true) { global $updraftplus; try { while ('/' == substr($path, 0, 1)) { $path = substr($path, 1); } $cache_key = empty($path) ? '/' : $path; if (!empty($this->ids_from_paths) && isset($this->ids_from_paths[$cache_key])) { return $this->ids_from_paths[$cache_key]; } $current_parent = $this->root_id(); $current_path = '/'; if (!empty($path)) { foreach (explode('/', $path) as $element) { $found = false; $sub_items = $this->get_subitems($current_parent, 'dir', $element); foreach ($sub_items as $item) { try { if ($item->getTitle() == $element) { $found = true; $current_path .= $element . '/'; $current_parent = $item->getId(); break; } } catch (Exception $e) { $updraftplus->log("Google Drive id_from_path: exception: " . $e->getMessage() . ' (line: ' . $e->getLine() . ', file: ' . $e->getFile() . ')'); } } if (!$found) { $ref = new Google_Service_Drive_ParentReference(); $ref->setId($current_parent); $dir = new Google_Service_Drive_DriveFile(); $dir->setMimeType('application/vnd.google-apps.folder'); $dir->setParents(array($ref)); $dir->setTitle($element); $updraftplus->log("Google Drive: creating path: " . $current_path . $element); $dir = $this->service->files->insert($dir, array('mimeType' => 'application/vnd.google-apps.folder')); $current_path .= $element . '/'; $current_parent = $dir->getId(); } } } if (empty($this->ids_from_paths)) { $this->ids_from_paths = array(); } $this->ids_from_paths[$cache_key] = $current_parent; return $current_parent; } catch (Exception $e) { $msg = $e->getMessage(); $updraftplus->log("Google Drive id_from_path failure: exception (" . get_class($e) . "): " . $msg . ' (line: ' . $e->getLine() . ', file: ' . $e->getFile() . ')'); if (is_a($e, 'Google_Service_Exception') && false !== strpos($msg, 'Invalid json in service response') && function_exists('mb_strpos')) { // Aug 2015: saw a case where the gzip-encoding was not removed from the result // https://stackoverflow.com/questions/10975775/how-to-determine-if-a-string-was-compressed $is_gzip = false !== mb_strpos($msg, "" . "‹" . ""); if ($is_gzip) { $updraftplus->log("Error: Response appears to be gzip-encoded still; something is broken in the client HTTP stack, and you should define UPDRAFTPLUS_GOOGLEDRIVE_DISABLEGZIP as true in your wp-config.php to overcome this."); } } # One retry return $retry ? $this->id_from_path($path, false) : false; } }
public function Customer_FolderCreation($service, $title, $description, $parentId) { $file = new Google_Service_Drive_DriveFile(); $file->setTitle($title); $file->setDescription($description); $file->setMimeType('application/vnd.google-apps.folder'); if ($parentId != null) { $parent = new Google_Service_Drive_ParentReference(); $parent->setId($parentId); $file->setParents(array($parent)); } try { $createdFile = $service->files->insert($file, array( 'mimeType' => 'application/vnd.google-apps.folder', )); return $createdFile->id; } catch (Exception $e) { return 0; } }
<?php require_once 'vendor/google/apiclient/src/Google/Client.php'; require_once 'vendor/google/apiclient/src/Google/Service/Drive.php'; $client = new Google_Client(); $client->setClientId('<YOUR_CLIENT_ID>'); $client->setClientSecret('<YOUR_CLIENT_SECRET>'); $client->setRedirectUri('<YOUR_REGISTERED_REDIRECT_URI>'); $client->setScopes(array('https://www.googleapis.com/auth/drive.file')); $session_start(); if (isset($_GET['code']) || isset($_SESSION['access_token']) && $_SESSION['access_token']) { if (isset($_GET['code'])) { $client->authenticate($_GET['code']); $_SESSION['access_token'] = $client->getAccessToken(); } else { $client->setAccessToken($_SESSION['access_token']); } $service = new Google_Service_Drive($client); $file = new Google_Service_Drive_DriveFile(); $file->setTitle('image.jpg'); $file->setDescription('image'); $file->setMimeType('image/jpeg'); $data = file_get_contents('image.jpg'); $createdFile = $service->files->insert($file, array('data' => $data, 'mimeType' => 'image/jpeg', 'uploadType' => 'multipart')); print_r($createdFile); } else { $authUrl = $client->createAuthUrl(); header('Location: ' . $authUrl); exit; }
/** * Uploads files to the Google drive. * @param $service the Google drive service. * @param string $filePath the directory location where to look for the files. * @param string $fileName the name of the file to be uploaded. * @param string $mimeType the mimeType of the file. * @param string $destinationFolder the directory on the Google drive. * @return string the expanded path. */ function gfUploadFile($client, $service, $filePath, $fileName, $mimeType, $destinationFolder) { $file = new Google_Service_Drive_DriveFile(); $file->setTitle($fileName); $file->setDescription($fileName); $file->setMimeType($fileName); if ($destinationFolder != "root") { $parent = new Google_Service_Drive_ParentReference(); $parent->setId(getParentDirectoryId($service, $destinationFolder)); $file->setParents(array($parent)); } $client->setDefer(true); $chunkSizeBytes = 1 * 1024 * 1024; $request = $service->files->insert($file); // Create a media file upload to represent our upload process. $media = new Google_Http_MediaFileUpload($client, $request, $mimeType, null, true, $chunkSizeBytes); $media->setFileSize(filesize($filePath . "/" . $fileName)); // Upload the various chunks. $status will be false until the process is // complete. $status = false; $handle = fopen($filePath . "/" . $fileName, "rb"); while (!$status && !feof($handle)) { $chunk = fread($handle, $chunkSizeBytes); $status = $media->nextChunk($chunk); } // The final value of $status will be the data from the API for the object // that has been uploaded. $result = false; if ($status != false) { $result = $status; } fclose($handle); // Reset to the client to execute requests immediately in the future. $client->setDefer(false); return $result; }
function copy_spreadsheet($morsle, $title, $template, $collectionid = null) { $service = new Google_Service_Drive($morsle->client); $file = new Google_Service_Drive_DriveFile(); $file->setTitle($title); // Set the parent folder. if ($collectionid !== null) { $parent = new Google_Service_Drive_ParentReference(); $parent->setId($collectionid); $file->setParents(array($parent)); } $result2 = $service->files->copy($template, $file); return $result2->id; }
public static function createFolder($settings, $parentID, $folderName) { if ('' == $parentID) { $parentID = 'root'; } $settings = self::_normalizeSettings($settings); if (false === ($settings = self::_connect($settings))) { $error = 'Error #2378327: Unable to connect with Google Drive. See log for details.'; echo $error; pb_backupbuddy::status('error', $error); return false; } //Insert a folder $driveFile = new Google_Service_Drive_DriveFile(); $driveFile->setTitle($folderName); //$driveFile->setParents( array( $parentID ) ); $driveFile->setMimeType('application/vnd.google-apps.folder'); // Set the parent folder. if ('root' != $parentID) { $parentsCollectionData = new Google_Service_Drive_ParentReference(); $parentsCollectionData->setId($parentID); $driveFile->setParents(array($parentsCollectionData)); } try { $insertRequest = self::$_drive->files->insert($driveFile); return array($insertRequest->id, $insertRequest->title); } catch (Exception $e) { global $pb_backupbuddy_destination_errors; $pb_backupbuddy_destination_errors[] = $e->getMessage(); $error = $e->getMessage(); echo $error; pb_backupbuddy::status('error', $error); return false; } }
function createFolder(&$service, $title, $description, $parentId, &$configObj) { for ($n = 0; $n < 5; ++$n) { try { $file = new Google_Service_Drive_DriveFile(); $file->setTitle($title); $file->setDescription($description); $file->setMimeType("application/vnd.google-apps.folder"); // Set the parent folder. if ($parentId != null) { $parent = new Google_Service_Drive_ParentReference(); $parent->setId($parentId); $file->setParents(array($parent)); } $createdFile = $service->files->insert($file, array()); return $createdFile; } catch (Google_Exception $e) { if ($e->getCode() == 403 || $e->getCode() == 503) { $logline = date('Y-m-d H:i:s') . " Error: " . $e->getMessage() . "\n"; $logline = $logline . date('Y-m-d H:i:s') . "Retrying... \n"; fwrite($configObj->logFile, $logline); // Apply exponential backoff. usleep((1 << $n) * 1000000 + rand(0, 1000000)); } } catch (Exception $e) { $logline = date('Y-m-d H:i:s') . "Unable to create folder.\n"; $logline = $logline . "Reason: " . $e->getCode() . " : " . $e->getMessage() . "\n"; fwrite($configObj->logFile, $logline); //If unable to create folder because of unrecognized error, return nothing return null; } } }
public function CreateFile($oAccount, $sType, $sPath, $sFileName, $mData, &$bResult, &$bBreak) { $oClient = $this->GetClient($oAccount, $sType); if ($oClient) { $bResult = false; $bBreak = true; $sMimeType = \MailSo\Base\Utils::MimeContentType($sFileName); $file = new Google_Service_Drive_DriveFile(); $file->setTitle($sFileName); $file->setMimeType($sMimeType); $sPath = trim($sPath, '/'); // Set the parent folder. if ($sPath != null) { $parent = new Google_Service_Drive_ParentReference(); $parent->setId($sPath); $file->setParents(array($parent)); } $oDrive = new Google_Service_Drive($oClient); try { $sData = ''; if (is_resource($mData)) { rewind($mData); $sData = stream_get_contents($mData); } else { $sData = $mData; } $oDrive->files->insert($file, array('data' => $sData, 'mimeType' => $sMimeType, 'uploadType' => 'media')); $bResult = true; } catch (Exception $ex) { $bResult = false; } } }
$children = $service->children->listChildren($folderid); // $root_filearray=$children->getItems(); // foreach ($root_filearray as $child) { // if($service->files->get($child->getId())->getExplicitlyTrashed()==1)continue; // $rootfold_title=$service->files->get($child->getId())->title; // if($login_empidarray[$i]!=$rootfold_title)continue; // $emp_folderid=$service->files->get($child->getId())->id; // echo $emp_folderid; // break; // } // if($emp_folderid=="") // { $newFolder = new Google_Service_Drive_DriveFile(); $newFolder->setMimeType('application/vnd.google-apps.folder'); $newFolder->setTitle($login_empidarray[$i]); if ($folderid != null) { $parent = new Google_Service_Drive_ParentReference(); $parent->setId($folderid); $newFolder->setParents(array($parent)); } try { $folderData = $service->files->insert($newFolder); } catch (Google_Service_Exception $e) { echo 'Error while creating <br>Message: '.$e->getMessage(); die(); } // } // else // continue;
/** * Upload file * @param string $directoryId (parent id) * @param string $filename * @param string $content * @param string $mimetype * @return handle */ public function upload($directoryId, $filename, $content, $mimetype = 'text/plain') { $parent = new \Google_Service_Drive_ParentReference(); $parent->setId($directoryId); $file = new \Google_Service_Drive_DriveFile(); $file->setTitle($filename); $file->setDescription($filename); $file->setMimeType('text/plain'); $file->setParents(array($parent)); $createdFile = $this->service->files->insert($file, array('data' => $content, 'mimeType' => $mimetype, 'uploadType' => 'media')); return $createdFile; }
} if (file_exists("token")) { $tok = file_get_contents("token"); $client->setAccessToken($tok); if ($client->isAccessTokenExpired()) { unset($_SESSION['upload_token']); @unlink("token"); } } else { $authUrl = $client->createAuthUrl(); } if ($client->getAccessToken()) { @file_put_contents("now-wc.txt", "point2.1 getAccessToken.file:" . "files/" . $newfilename2412, FILE_APPEND); $file = new Google_Service_Drive_DriveFile(); //$file->setTitle($out_file_name); $file->setTitle($newfilename2412); if ($ftype == 'contract' or $ftype == 'invoice' or $ftype == 'act') { @file_put_contents("now-wc.txt", "point2.1.1 contract", FILE_APPEND); //$newfilename2412 //array( // 'data' => file_get_contents("files/".$out_file_name), // 'mimeType' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', // 'uploadType' => 'media', // 'convert' => 'true' //) $result = $service->files->insert($file, array('data' => file_get_contents("files/" . $newfilename2412), 'mimeType' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'uploadType' => 'media', 'convert' => 'true')); } else { $result = $service->files->insert($file, array('data' => file_get_contents("files/" . $newfilename2412), 'mimeType' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'uploadType' => 'media', 'convert' => 'true')); } } elseif (isset($authUrl)) { @file_put_contents("now-wc.txt", "point4.2", FILE_APPEND);
************************************************/ if ($_SERVER['REQUEST_METHOD'] == 'POST' && $client->getAccessToken()) { // We'll setup an empty 1MB file to upload. DEFINE("TESTFILE", 'testfile-small.txt'); if (!file_exists(TESTFILE)) { $fh = fopen(TESTFILE, 'w'); fseek($fh, 1024 * 1024); fwrite($fh, "!", 1); fclose($fh); } // This is uploading a file directly, with no metadata associated. $file = new Google_Service_Drive_DriveFile(); $result = $service->files->insert($file, array('data' => file_get_contents(TESTFILE), 'mimeType' => 'application/octet-stream', 'uploadType' => 'media')); // Now lets try and send the metadata as well using multipart! $file = new Google_Service_Drive_DriveFile(); $file->setTitle("Hello World!"); $result2 = $service->files->insert($file, array('data' => file_get_contents(TESTFILE), 'mimeType' => 'application/octet-stream', 'uploadType' => 'multipart')); } ?> <div class="box"> <?php if (isset($authUrl)) { ?> <div class="request"> <a class='login' href='<?php echo $authUrl; ?> '>Connect Me!</a> </div> <?php
public function touch($path, $mtime = null) { $file = $this->getDriveFile($path); $result = false; if ($file) { if (isset($mtime)) { // This is just RFC3339, but frustratingly, GDrive's API *requires* // the fractions portion be present, while no handy PHP constant // for RFC3339 or ISO8601 includes it. So we do it ourselves. $file->setModifiedDate(date('Y-m-d\\TH:i:s.uP', $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_Service_Drive_DriveFile(); $file->setTitle(basename($path)); $parent = new \Google_Service_Drive_ParentReference(); $parent->setId($parentFolder->getId()); $file->setParents(array($parent)); $result = $this->service->files->insert($file); } } if ($result) { $this->setDriveFile($path, $result); } return (bool) $result; }
private function _copyFolderRecursive(UseyourDrive_Node $templatefolder, UseyourDrive_Node $newfolder) { if ($templatefolder !== null && $templatefolder !== false && $templatefolder->hasItem() && $newfolder !== null && $newfolder !== false && $newfolder->hasItem()) { $template_entry = $templatefolder->getItem(); $newfolder_entry = $newfolder->getItem(); if ($templatefolder->hasChildren()) { foreach ($templatefolder->getChildren() as $cached_child) { $child = $cached_child->getItem(); if ($child->getMimeType() === 'application/vnd.google-apps.folder') { /* Create child folder in user folder */ $newchildfolder = new Google_Service_Drive_DriveFile(); $newchildfolder->setTitle($child->getTitle()); $newchildfolder->setMimeType('application/vnd.google-apps.folder'); $newParent = new Google_Service_Drive_ParentReference(); $newParent->setId($newfolder_entry->getId()); $newchildfolder->setParents(array($newParent)); try { $a = 1; $newchildentry = $this->googleDriveService->files->insert($newchildfolder, array("userIp" => $this->userip)); } catch (Exception $ex) { continue; } $cachednewchildentry = $this->cache->addToCache($newchildentry); /* Copy contents of child folder to new create child user folder */ $cached_child_folder = $this->getFolder(false, $child->getId(), false, false); if ($cached_child_folder !== false && $cached_child_folder['folder'] !== false) { $this->_copyFolderRecursive($cached_child_folder['folder'], $cachednewchildentry); } } else { /* Copy file to new folder */ $newfile = new Google_Service_Drive_DriveFile(); $newfile->setTitle($child->getTitle()); $newParent = new Google_Service_Drive_ParentReference(); $newParent->setId($newfolder_entry->getId()); $newfile->setParents(array($newParent)); try { $a = 1; $newchildentry = $this->googleDriveService->files->copy($child->getId(), $newfile, array("userIp" => $this->userip)); } catch (Exception $ex) { continue; } $cachednewchildentry = $this->cache->addToCache($newchildentry); } } } } }
function UploadEmployeeFiles($formname, $loginid_result) { global $con, $ClientId, $ClientSecret, $RedirectUri, $DriveScopes, $CalenderScopes, $Refresh_Token, $emp_uldid; $loginid = $loginid_result; $emp_uploadfilelist = array(); $login_empid = getEmpfolderName($loginid); // echo $login_empid;exit; $select_folderid = mysqli_query($con, "SELECT * FROM USER_RIGHTS_CONFIGURATION WHERE URC_ID=13"); if ($row = mysqli_fetch_array($select_folderid)) { $folderid = $row["URC_DATA"]; } $drive = new Google_Client(); $Client = get_servicedata(); $ClientId = $Client[0]; $ClientSecret = $Client[1]; $RedirectUri = $Client[2]; $DriveScopes = $Client[3]; $CalenderScopes = $Client[4]; $Refresh_Token = $Client[5]; $drive->setClientId($ClientId); $drive->setClientSecret($ClientSecret); $drive->setRedirectUri($RedirectUri); $drive->setScopes(array($DriveScopes, $CalenderScopes)); $drive->setAccessType('online'); $refresh_token = $Refresh_Token; $drive->refreshToken($refresh_token); $service = new Google_Service_Drive($drive); $logincre_foldername = $login_empid; $emp_folderid = ""; $emp_uploadfilenamelist = array(); $emp_uploadfileidlist = array(); $children = $service->children->listChildren($folderid); $root_filearray = $children->getItems(); foreach ($root_filearray as $child) { if ($service->files->get($child->getId())->getExplicitlyTrashed() == 1) { continue; } $rootfold_title = $service->files->get($child->getId())->title; $split_folderid = explode(" ", $rootfold_title); if (strcasecmp($emp_uldid, $split_folderid[count($split_folderid) - 1]) != 0) { continue; } $emp_folderid = $service->files->get($child->getId())->id; if ($rootfold_title != $login_empid) { // //rename folder for loging updation start renamefile($service, $logincre_foldername, $emp_folderid); } //end $emp_uploadfilenamelist = array(); $children1 = $service->children->listChildren($child->getId()); $child_filearray = $children1->getItems(); sort($child_filearray); foreach ($child_filearray as $child1) { if ($service->files->get($child1->getId())->getExplicitlyTrashed() == 1) { continue; } $emp_uploadfilenamelist[] = $service->files->get($child1->getId())->title; } break; } sort($emp_uploadfilenamelist); $emp_uploadfileidlist = array(); $emp_uploadfilelinklist = array(); for ($f = 0; $f < count($emp_uploadfilenamelist); $f++) { $children1 = $service->children->listChildren($emp_folderid); $filearray1 = $children1->getItems(); foreach ($filearray1 as $child1) { if ($service->files->get($child1->getId())->getExplicitlyTrashed() == 1) { continue; } if ($service->files->get($child1->getId())->title == $emp_uploadfilenamelist[$f]) { $emp_uploadfileidlist[] = $service->files->get($child1->getId())->id; $emp_uploadfilelinklist[] = $service->files->get($child1->getId())->alternateLink; } } } if ($emp_folderid == "" && $formname == "login_creation") { $newFolder = new Google_Service_Drive_DriveFile(); $newFolder->setMimeType('application/vnd.google-apps.folder'); $newFolder->setTitle($logincre_foldername); if ($folderid != null) { $parent = new Google_Service_Drive_ParentReference(); $parent->setId($folderid); $newFolder->setParents(array($parent)); } try { $folderData = $service->files->insert($newFolder); } catch (Google_Service_Exception $e) { echo 'Error while creating <br>Message: ' . $e->getMessage(); die; } $emp_folderid = $folderData->id; } if ($formname == "login_fetch") { if ($emp_folderid == "") { echo "Error:Folder id Not present"; exit; } $emp_uploadfiles = array($emp_uploadfileidlist, $emp_uploadfilenamelist, $emp_uploadfilelinklist); return $emp_uploadfiles; } return $emp_folderid; }