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());
    }
}
 /**
  * @param \Google_Service_Drive $service
  *
  * @return \Google_Service_Drive_ParentReference|null
  *
  * @throws \Symfony\Component\Security\Core\Exception\LockedException
  */
 protected function getParentFolder(\Google_Service_Drive $service)
 {
     $parts = explode('/', trim($this->remotePath, '/'));
     $folderId = null;
     foreach ($parts as $name) {
         $q = 'mimeType="application/vnd.google-apps.folder" and title contains "' . $name . '"';
         if ($folderId) {
             $q .= sprintf(' and "%s" in parents', $folderId);
         }
         $folders = $service->files->listFiles(array('q' => $q))->getItems();
         if (count($folders) == 0) {
             //TODO create the missing folder.
             throw new \LogicException('Remote path does not exist.');
         } else {
             /* @var \Google_Service_Drive_DriveFile $folders[0] */
             $folderId = $folders[0]->id;
         }
     }
     if (!$folderId) {
         return;
     }
     $parent = new \Google_Service_Drive_ParentReference();
     $parent->setId($folderId);
     return $parent;
 }
示例#3
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();
     }
 }
示例#4
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;
 }
 public static function uploadFile($access_token, $uploadFile, $fileName, $config)
 {
     if (!isset($access_token)) {
         return;
     }
     $userId = \HttpReceiver\HttpReceiver::get('userId', 'string');
     $client = self::getGoogleClient($config);
     try {
         $access_token = (array) $access_token;
         $client->setAccessToken($access_token);
     } catch (\InvalidArgumentException $e) {
         return array('status' => 'error', 'msg' => 'refreshToken', 'url' => self::auth($userId, $config));
     }
     $service = new \Google_Service_Drive($client);
     //Insert a file
     $file = new \Google_Service_Drive_DriveFile();
     if (!isset($fileName) || strlen($fileName) == 0 || $fileName == '0') {
         $tmp = explode('/', $uploadFile);
         $fileName = $tmp[sizeof($tmp) - 1];
     } else {
         $fileName .= '.pdf';
     }
     $file->setTitle($fileName);
     $file->setDescription('A test document');
     $file->setMimeType('application/pdf');
     $data = file_get_contents($uploadFile);
     $folderInfo = self::getFolder($access_token, $config);
     $id = 0;
     if ($folderInfo['status'] === 'ok') {
         $id = $folderInfo['id'];
     } else {
         return array('status' => 'error', 'msg' => 'refreshToken', 'url' => self::auth($userId, $config));
     }
     $parent = new \Google_Service_Drive_ParentReference();
     $parent->setId($id);
     $file->setParents(array($parent));
     try {
         $createdFile = $service->files->insert($file, array('data' => $data, 'mimeType' => 'application/pdf', 'uploadType' => 'resumable'));
     } catch (\Exception $e) {
         return array('status' => 'error', 'msg' => 'refreshToken', 'url' => self::auth($userId, $config));
     }
     if (isset($createdFile) && isset($createdFile['id']) && strlen($createdFile['id']) > 0) {
         return array('status' => 'ok');
     } else {
         return array('status' => 'error', 'msg' => 'refreshToken', 'url' => self::auth($userId, $config));
     }
 }
示例#6
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();
    }
}
示例#7
0
 /**
  * Upload a file to current directory
  */
 public function uploadFile($localPath)
 {
     if (!file_exists($localPath)) {
         throw new \Exception('File not exists');
     }
     $file = new \Google_Service_Drive_DriveFile();
     $file->title = basename($localPath);
     if ($this->gdriveFolder) {
         $parent = new \Google_Service_Drive_ParentReference();
         $parent->setId($this->gdriveFolder->getId());
         $file->setParents(array($parent));
     }
     $chunkSizeBytes = $this->chunkSizeBytes;
     $this->client->setDefer(true);
     $request = $this->drive->files->insert($file);
     $media = new \Google_Http_MediaFileUpload($this->client, $request, 'text/plain', null, true, $chunkSizeBytes);
     $media->setFileSize(filesize($localPath));
     // Upload the various chunks. $status will be false until the process is
     // complete.
     $status = false;
     $handle = fopen($localPath, "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.
     $this->client->setDefer(false);
     if ($result) {
         return new File($result, $this);
     }
 }
    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;
        }
    }
示例#9
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;
}
示例#10
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;
 }
/**
 * 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 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;
        }
    }
}
 /**
  * rename() wrapper
  *
  * @param string $path_from Path (from)
  * @param string $path_to   Path (to)
  *
  * @return boolean
  */
 public function rename($path_from, $path_to)
 {
     $result = false;
     if (file_exists($path_from) && is_dir($path_from)) {
         $from = $this->getItemByPath($this->convertPathToFS($path_from));
         $parentTo = dirname($this->convertPathToFS($path_to));
         mkdir($this->convertPathToURL($parentTo));
         $from->setTitle(basename($this->convertPathToFS($path_to)));
         $ref = new \Google_Service_Drive_ParentReference();
         $parentToFile = $this->getItemByPath($parentTo);
         $ref->setId($parentToFile->getId());
         $from->setParents(array($ref));
         static::$service->files->update($from->getId(), $from);
         $result = true;
     }
     return $result;
 }
示例#14
0
 /**
  *	Drive Create File
  */
 public function createFile($title, $parentId, $mimeType = 'text')
 {
     // Get the API client and construct the service object.
     $client = $this->getClient();
     $service = new \Google_Service_Drive($client);
     $file = new \Google_Service_Drive_DriveFile();
     $file->setTitle($title);
     $file->setMimeType($mimeType);
     $parent = new \Google_Service_Drive_ParentReference();
     $parent->setId($parentId);
     $file->setParents([$parent]);
     $data = "basics\nand stuff";
     $createdFile = $service->files->insert($file, array('data' => $data, 'mimeType' => $mimeType));
     # WP crap
     wp_die();
 }
示例#15
0
 /**
  * Uploads backup file from server to Google Drive.
  *
  * @param array $args arguments passed to the function
  *                    [task_name] -> Task name for wich we are uploading
  *                    [task_result_key] -> Result key that we are uploading
  *                    [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
  */
 public function google_drive_backup($args)
 {
     mwp_register_autoload_google();
     $googleClient = new Google_ApiClient();
     $googleClient->setAccessToken($args['google_drive_token']);
     $googleDrive = new Google_Service_Drive($googleClient);
     mwp_logger()->info('Fetching Google Drive root folder ID');
     try {
         $about = $googleDrive->about->get();
         $rootFolderId = $about->getRootFolderId();
     } catch (Exception $e) {
         mwp_logger()->error('Error while fetching Google Drive root folder ID', array('exception' => $e));
         return array('error' => 'Error while fetching Google Drive root folder ID: ' . $e->getMessage());
     }
     mwp_logger()->info('Loading Google Drive backup directory');
     try {
         $rootFiles = $googleDrive->files->listFiles(array("q" => "title='" . addslashes($args['google_drive_directory']) . "' and '{$rootFolderId}' in parents and trashed = false"));
     } catch (Exception $e) {
         mwp_logger()->error('Error while loading Google Drive backup directory', array('exception' => $e));
         return array('error' => 'Error while loading Google Drive backup directory: ' . $e->getMessage());
     }
     if ($rootFiles->offsetExists(0)) {
         $backupFolder = $rootFiles->offsetGet(0);
     } else {
         try {
             mwp_logger()->info('Creating Google Drive backup directory');
             $newBackupFolder = new Google_Service_Drive_DriveFile();
             $newBackupFolder->setTitle($args['google_drive_directory']);
             $newBackupFolder->setMimeType('application/vnd.google-apps.folder');
             if ($rootFolderId) {
                 $parent = new Google_Service_Drive_ParentReference();
                 $parent->setId($rootFolderId);
                 $newBackupFolder->setParents(array($parent));
             }
             $backupFolder = $googleDrive->files->insert($newBackupFolder);
         } catch (Exception $e) {
             mwp_logger()->info('Error while creating Google Drive backup directory', array('exception' => $e));
             return array('error' => 'Error while creating Google Drive backup directory: ' . $e->getMessage());
         }
     }
     if ($args['google_drive_site_folder']) {
         try {
             mwp_logger()->info('Fetching Google Drive site directory');
             $siteFolderTitle = $this->site_name;
             $backupFolderId = $backupFolder->getId();
             $driveFiles = $googleDrive->files->listFiles(array("q" => "title='" . addslashes($siteFolderTitle) . "' and '{$backupFolderId}' in parents and trashed = false"));
         } catch (Exception $e) {
             mwp_logger()->info('Error while fetching Google Drive site directory', array('exception' => $e));
             return array('error' => 'Error while fetching Google Drive site directory: ' . $e->getMessage());
         }
         if ($driveFiles->offsetExists(0)) {
             $siteFolder = $driveFiles->offsetGet(0);
         } else {
             try {
                 mwp_logger()->info('Creating Google Drive site directory');
                 $_backup_folder = new Google_Service_Drive_DriveFile();
                 $_backup_folder->setTitle($siteFolderTitle);
                 $_backup_folder->setMimeType('application/vnd.google-apps.folder');
                 if (isset($backupFolder)) {
                     $_backup_folder->setParents(array($backupFolder));
                 }
                 $siteFolder = $googleDrive->files->insert($_backup_folder, array());
             } catch (Exception $e) {
                 mwp_logger()->info('Error while creating Google Drive site directory', array('exception' => $e));
                 return array('error' => 'Error while creating Google Drive site directory: ' . $e->getMessage());
             }
         }
     } else {
         $siteFolder = $backupFolder;
     }
     $file_path = explode('/', $args['backup_file']);
     $backupFile = new Google_Service_Drive_DriveFile();
     $backupFile->setTitle(end($file_path));
     $backupFile->setDescription('Backup file of site: ' . $this->site_name . '.');
     if ($siteFolder != null) {
         $backupFile->setParents(array($siteFolder));
     }
     $googleClient->setDefer(true);
     // Deferred client returns request object.
     /** @var Google_Http_Request $request */
     $request = $googleDrive->files->insert($backupFile);
     $chunkSize = 1024 * 1024 * 4;
     $media = new Google_Http_MediaFileUpload($googleClient, $request, 'application/zip', null, true, $chunkSize);
     $fileSize = filesize($args['backup_file']);
     $media->setFileSize($fileSize);
     mwp_logger()->info('Uploading backup file to Google Drive; file size is {backup_size}', array('backup_size' => mwp_format_bytes($fileSize)));
     // Upload the various chunks. $status will be false until the process is
     // complete.
     $status = false;
     $handle = fopen($args['backup_file'], 'rb');
     $started = microtime(true);
     $lastNotification = $started;
     $lastProgress = 0;
     $threshold = 1;
     $uploaded = 0;
     $started = microtime(true);
     while (!$status && !feof($handle)) {
         $chunk = fread($handle, $chunkSize);
         $newChunkSize = strlen($chunk);
         if (($elapsed = microtime(true) - $lastNotification) > $threshold) {
             $lastNotification = microtime(true);
             mwp_logger()->info('Upload progress: {progress}% (speed: {speed}/s)', array('progress' => round($uploaded / $fileSize * 100, 2), 'speed' => mwp_format_bytes(($uploaded - $lastProgress) / $elapsed)));
             $lastProgress = $uploaded;
             echo " ";
             flush();
         }
         $uploaded += $newChunkSize;
         $status = $media->nextChunk($chunk);
     }
     fclose($handle);
     if (!$status instanceof Google_Service_Drive_DriveFile) {
         mwp_logger()->error('Upload to Google Drive failed', array('status' => $status));
         return array('error' => 'Upload to Google Drive was not successful.');
     }
     $this->tasks[$args['task_name']]['task_results'][$args['task_result_key']]['google_drive']['file_id'] = $status->getId();
     mwp_logger()->info('Upload to Google Drive completed; average speed is {speed}/s', array('speed' => mwp_format_bytes(round($fileSize / (microtime(true) - $started)))));
     return true;
 }
示例#16
0
/**
 * Insert new file.
 *
 * @param Google_Service_Drive $service Drive API service instance.
 * @param string $title Title of the file to insert, including the extension.
 * @param string $description Description of the file to insert.
 * @param string $parentId Parent folder's ID.
 * @param string $mimeType MIME type of the file to insert.
 * @param string $filename Filename of the file to insert.
 * @return Google_Service_Drive_DriveFile The file that was inserted. NULL is
 *     returned if an API error occurred.
 */
function insertFile($service, $title, $description, $parentId, $mimeType, $filename, $properties = [])
{
    $file = new Google_Service_Drive_DriveFile();

    $file->setTitle($title);
    $file->setDescription($description);
    $file->setMimeType($mimeType);
    $file->setProperties($properties);

    // 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,
            'mimeType' => $mimeType,
            'uploadType' => 'media',
            'convert' => true,
        ));

        // Uncomment the following line to print the File ID
        // print 'File ID: %s' % $createdFile->getId();

        return $createdFile;
    } catch (Exception $e) {
        catchGoogleExceptions($e);
    }
}
示例#17
0
 public function insert_public_folder($service)
 {
     $parentId = get_option("flowdrive_basefolder");
     $file = new \Google_Service_Drive_DriveFile();
     $file->setTitle('flowdrive');
     $file->setMimeType('application/vnd.google-apps.folder');
     // Set base folder
     if ($parentId) {
         $parent = new \Google_Service_Drive_ParentReference();
         $parent->setId($parentId);
         $file->setParents([$parent]);
     }
     $createdFile = $service->files->insert($file, ['mimeType' => 'application/vnd.google-apps.folder']);
     $permission = new \Google_Service_Drive_Permission();
     $permission->setValue('');
     $permission->setType('anyone');
     $permission->setRole('reader');
     $service->permissions->insert($createdFile->getId(), $permission);
     return $createdFile->getId();
 }
    public function getFileIdByName($name)
    {
        $files = $this->sef->files->listFiles();
        foreach ($files['items'] as $item) {
            if ($item['title'] == $name) {
                return $item['id'];
            }
        }
        return false;
    }
}
//if( $_SERVER['argc'] != 2 ) {
//echo "ERROR: no file selected\n";
//die();
//}
$path = "/home/anpac/public_html/test.txt";
// $_SERVER['argv'][1];
printf("Uploading %s to Google Drive\n", $path);
$service = new DriveServiceHelper(CLIENT_ID, SERVICE_ACCOUNT_NAME, KEY_PATH);
echo "Creating folder...\n";
$folderId = $service->getFileIdByName(BACKUP_FOLDER);
if (!$folderId) {
    echo "Creating folder...\n";
    $folderId = $service->createFolder(BACKUP_FOLDER);
    $service->setPermissions($folderId, SHARE_WITH_GOOGLE_EMAIL);
}
$fileParent = new Google_Service_Drive_ParentReference();
$fileParent->setId($folderId);
$fileId = $service->createFileFromPath($path, $path, $fileParent);
printf("File: %s created\n", $fileId);
$service->setPermissions($fileId, SHARE_WITH_GOOGLE_EMAIL);
 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;
         }
     }
 }
function insertFile($service, $title, $description, $parentId,$mimeType,$uploadfilename)
{
    $file = new Google_Service_Drive_DriveFile();
    $file->setTitle($title);
    $file->setDescription($description);
    $file->setMimeType($mimeType);
    if ($parentId != null) {
        $parent = new Google_Service_Drive_ParentReference();
        $parent->setId($parentId);
        $file->setParents(array($parent));
    }
    try
    {
        $data =file_get_contents($uploadfilename);
        $createdFile = $service->files->insert($file, array(
            'data' => $data,
            'mimeType' => $mimeType,
            'uploadType' => 'media',
        ));

        $fileid = $createdFile->getId();
        $fileflag=1;
    }
    catch (Exception $e)
    {
        $fileflag=0;
    }
    $finalarry=[$fileid,$fileflag];
    return $finalarry;
}
示例#21
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;
     }
 }
 /**
  * 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;
 }
示例#23
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;
 }
示例#24
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;
 }
示例#25
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();
    }
}
示例#26
0
 /**
  * @param $baseFolderId
  * @param $folderName
  * @return Google_Service_Drive_DriveFile
  * @throws \Exception
  */
 public function createFolder(string $baseFolderId, string $folderName) : Google_Service_Drive_DriveFile
 {
     $file = new Google_Service_Drive_DriveFile();
     $file->title = $folderName;
     $file->setMimeType('application/vnd.google-apps.folder');
     $parent = new \Google_Service_Drive_ParentReference();
     $parent->setId($baseFolderId);
     $file->setParents([$parent]);
     $request = $this->service->files->insert($file);
     $batch = new \Google_Http_Batch($this->client);
     $batch->add($request);
     $response = $batch->execute();
     $result = array_pop($response);
     if ($result instanceof \Google_Service_Exception) {
         var_dump($result);
         throw new \Exception('Google Service returned Exception');
     } else {
         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;
 }
示例#28
0
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;
}
示例#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);
                 }
             }
         }
     }
 }
        $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;

    }