示例#1
3
文件: googledrive.php 项目: xXLXx/ddc
 /**
  * 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());
    }
}
示例#3
2
<?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);
示例#4
1
 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);
 }
 /**
  * Create new file and write into it from file pointer.
  * Return new file path or false on error.
  *
  * @param resource $fp   file pointer
  * @param string   $dir  target dir path
  * @param string   $name file name
  * @param array    $stat file stat (required by some virtual fs)
  *
  * @return bool|string
  *
  * @author Dmitry (dio) Levashov
  **/
 protected function _save($fp, $path, $name, $stat)
 {
     if ($name !== '') {
         $path .= '/' . $name;
     }
     list($parentId, $itemId, $parent) = $this->_gd_splitPath($path);
     if ($name === '') {
         $stat['iid'] = $itemId;
     }
     if (!$stat || empty($stat['iid'])) {
         $opts = ['q' => sprintf('trashed=false and "%s" in parents and name="%s"', $parentId, $name), 'fields' => self::FETCHFIELDS_LIST];
         $srcFile = $this->_gd_query($opts);
         $srcFile = empty($srcFile) ? null : $srcFile[0];
     } else {
         $srcFile = $this->_gd_getFile($path);
     }
     try {
         $mode = 'update';
         $mime = isset($stat['mime']) ? $stat['mime'] : '';
         $file = new Google_Service_Drive_DriveFile();
         if ($srcFile) {
             $mime = $srcFile->getMimeType();
         } else {
             $mode = 'insert';
             $file->setName($name);
             $file->setParents([$parentId]);
         }
         if (!$mime) {
             $mime = self::mimetypeInternalDetect($name);
         }
         if ($mime === 'unknown') {
             $mime = 'application/octet-stream';
         }
         $file->setMimeType($mime);
         $size = 0;
         if (isset($stat['size'])) {
             $size = $stat['size'];
         } else {
             $fstat = fstat($fp);
             if (!empty($fstat['size'])) {
                 $size = $fstat['size'];
             }
         }
         // set chunk size (max: 100MB)
         $chunkSizeBytes = 100 * 1024 * 1024;
         if ($size > 0) {
             $memory = elFinder::getIniBytes('memory_limit');
             if ($memory) {
                 $chunkSizeBytes = min([$chunkSizeBytes, intval($memory / 4 / 256) * 256]);
             }
         }
         if ($size > $chunkSizeBytes) {
             $client = $this->client;
             // Call the API with the media upload, defer so it doesn't immediately return.
             $client->setDefer(true);
             if ($mode === 'insert') {
                 $request = $this->service->files->create($file, ['fields' => self::FETCHFIELDS_GET]);
             } else {
                 $request = $this->service->files->update($srcFile->getId(), $file, ['fields' => self::FETCHFIELDS_GET]);
             }
             // Create a media file upload to represent our upload process.
             $media = new Google_Http_MediaFileUpload($client, $request, $mime, null, true, $chunkSizeBytes);
             $media->setFileSize($size);
             // Upload the various chunks. $status will be false until the process is
             // complete.
             $status = false;
             while (!$status && !feof($fp)) {
                 elFinder::extendTimeLimit();
                 // read until you get $chunkSizeBytes from TESTFILE
                 // fread will never return more than 8192 bytes if the stream is read buffered and it does not represent a plain file
                 // An example of a read buffered file is when reading from a URL
                 $chunk = $this->_gd_readFileChunk($fp, $chunkSizeBytes);
                 $status = $media->nextChunk($chunk);
             }
             // The final value of $status will be the data from the API for the object
             // that has been uploaded.
             if ($status !== false) {
                 $obj = $status;
             }
             $client->setDefer(false);
         } else {
             $params = ['data' => stream_get_contents($fp), 'uploadType' => 'media', 'fields' => self::FETCHFIELDS_GET];
             if ($mode === 'insert') {
                 $obj = $this->service->files->create($file, $params);
             } else {
                 $obj = $this->service->files->update($srcFile->getId(), $file, $params);
             }
         }
         if ($obj instanceof Google_Service_Drive_DriveFile) {
             return $this->_joinPath($parent, $obj->getId());
         } else {
             return false;
         }
     } catch (Exception $e) {
         return $this->setError('GoogleDrive error: ' . $e->getMessage());
     }
 }
示例#6
0
 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;
 }
示例#7
0
 /**
  * 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!'));
         }
     }
 }
/**
 * 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>';
}
示例#9
0
文件: lib.php 项目: evltuma/moodle
 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;
 }
示例#10
0
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);
}
示例#11
0
 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();
     }
 }
 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'];
 }
示例#13
0
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();
    }
}
/**
 * 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;
}
 /**
  * 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;
 }
示例#17
0
/**
 * 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();
    }
}
示例#18
0
 private function upload_file($file, $parent_id, $try_again = true)
 {
     global $updraftplus;
     $opts = $this->get_opts();
     $basename = basename($file);
     $service = $this->service;
     $client = $this->client;
     # See: https://github.com/google/google-api-php-client/blob/master/examples/fileupload.php (at time of writing, only shows how to upload in chunks, not how to resume)
     $client->setDefer(true);
     $local_size = filesize($file);
     $gdfile = new Google_Service_Drive_DriveFile();
     $gdfile->title = $basename;
     $ref = new Google_Service_Drive_ParentReference();
     $ref->setId($parent_id);
     $gdfile->setParents(array($ref));
     $size = 0;
     $request = $service->files->insert($gdfile);
     $chunk_bytes = 1048576;
     $hash = md5($file);
     $transkey = 'gdresume_' . $hash;
     // This is unset upon completion, so if it is set then we are resuming
     $possible_location = $updraftplus->jobdata_get($transkey);
     if (is_array($possible_location)) {
         $headers = array('content-range' => "bytes */" . $local_size);
         $httpRequest = new Google_Http_Request($possible_location[0], 'PUT', $headers, '');
         $response = $this->client->getIo()->makeRequest($httpRequest);
         $can_resume = false;
         if (308 == $response->getResponseHttpCode()) {
             $range = $response->getResponseHeader('range');
             if (!empty($range) && preg_match('/bytes=0-(\\d+)$/', $range, $matches)) {
                 $can_resume = true;
                 $possible_location[1] = $matches[1] + 1;
                 $updraftplus->log("{$basename}: upload already began; attempting to resume from byte " . $matches[1]);
             }
         }
         if (!$can_resume) {
             $updraftplus->log("{$basename}: upload already began; attempt to resume did not succeed (HTTP code: " . $response->getResponseHttpCode() . ")");
         }
     }
     $media = new Google_Http_MediaFileUpload($client, $request, '.zip' == substr($basename, -4, 4) ? 'application/zip' : 'application/octet-stream', null, true, $chunk_bytes);
     $media->setFileSize($local_size);
     if (!empty($possible_location)) {
         $media->resumeUri = $possible_location[0];
         $media->progress = $possible_location[1];
         $size = $possible_location[1];
     }
     if ($size >= $local_size) {
         return true;
     }
     $status = false;
     if (false == ($handle = fopen($file, 'rb'))) {
         $updraftplus->log("Google Drive: failed to open file: {$basename}");
         $updraftplus->log("{$basename}: " . sprintf(__('%s Error: Failed to open local file', 'updraftplus'), 'Google Drive'), 'error');
         return false;
     }
     if ($size > 0 && 0 != fseek($handle, $size)) {
         $updraftplus->log("Google Drive: failed to fseek file: {$basename}, {$size}");
         $updraftplus->log("{$basename} (fseek): " . sprintf(__('%s Error: Failed to open local file', 'updraftplus'), 'Google Drive'), 'error');
         return false;
     }
     $pointer = $size;
     try {
         while (!$status && !feof($handle)) {
             $chunk = fread($handle, $chunk_bytes);
             # Error handling??
             $pointer += strlen($chunk);
             $status = $media->nextChunk($chunk);
             $updraftplus->jobdata_set($transkey, array($media->resumeUri, $media->getProgress()));
             $updraftplus->record_uploaded_chunk(round(100 * $pointer / $local_size, 1), $media->getProgress(), $file);
         }
     } catch (Google_Service_Exception $e) {
         $updraftplus->log("ERROR: Google Drive upload error (" . get_class($e) . "): " . $e->getMessage() . ' (line: ' . $e->getLine() . ', file: ' . $e->getFile() . ')');
         $client->setDefer(false);
         fclose($handle);
         $updraftplus->jobdata_delete($transkey);
         if (false == $try_again) {
             throw $e;
         }
         # Reset this counter to prevent the something_useful_happened condition's possibility being sent into the far future and potentially missed
         if ($updraftplus->current_resumption > 9) {
             $updraftplus->jobdata_set('uploaded_lastreset', $updraftplus->current_resumption);
         }
         return $this->upload_file($file, $parent_id, false);
     }
     // 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);
     $client->setDefer(false);
     $updraftplus->jobdata_delete($transkey);
     return true;
 }
示例#19
0
 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;
 }
示例#20
0
    $redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
    header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));
}
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'));
    }
示例#21
0
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;
}
示例#22
0
 /**
  * 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;
 }
 /**
  * Store data to Google Drive File
  * @param type $filedata File data to store
  * @param type $name Name of the file
  */
 public function storeFile($filedata = "", $name = "")
 {
     //Initiate file
     $gfile = new Google_Service_Drive_DriveFile();
     $gfile->setName($name);
     try {
         //Upload the file
         $result = $this->google_service->files->create($gfile, array('data' => $filedata, 'mimeType' => 'application/octet-stream', 'uploadType' => 'multipart'));
         return $result;
     } catch (Exception $ex) {
         echo "<pre>";
         print_r($ex->getMessage());
         return false;
     }
     return false;
 }
    for($i=0;$i<count($login_empidarray);$i++)
    {

        $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
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 Copy($oAccount, $sFromType, $sToType, $sFromPath, $sToPath, $sName, $sNewName, &$bResult, &$bBreak)
 {
     $oClient = $this->GetClient($oAccount, $sFromType);
     if ($oClient) {
         $bResult = false;
         $bBreak = true;
         $oDrive = new Google_Service_Drive($oClient);
         $sToPath = $sToPath === '' ? 'root' : trim($sToPath, '/');
         $parent = new Google_Service_Drive_ParentReference();
         $parent->setId($sToPath);
         $copiedFile = new Google_Service_Drive_DriveFile();
         //			$copiedFile->setTitle($sNewName);
         $copiedFile->setParents(array($parent));
         try {
             $oDrive->files->copy($sName, $copiedFile);
             $bResult = true;
         } catch (Exception $ex) {
             $bResult = false;
         }
     }
 }
 * file. For larger files, see fileupload.php.
 ************************************************/
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>
    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;
        }
    }
示例#29
0
 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);
                 }
             }
         }
     }
 }
示例#30
0
文件: init.php 项目: jimlongo56/rdiv
 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;
     }
 }