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());
    }
}
Beispiel #2
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);
Beispiel #3
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);
 }
 /**
  * Creates the Google Drive CDN folder on the google drive
  * @since 1.0
  *
  * @param null $folder
  *
  */
 public function create_folder($folder = null)
 {
     if (is_null($folder)) {
         $folder = home_url();
         $folder = str_replace('http://', '', $folder);
         $folder = str_replace('https://', '', $folder);
         $folder = sanitize_key($folder);
     }
     $service = new Google_Service_Drive($this->_google_drive_cdn->get_google_client());
     $file = new Google_Service_Drive_DriveFile();
     $file->setTitle($folder);
     $file->setDescription(home_url() . ' to Google Drive CDN Folder');
     $file->setMimeType('application/vnd.google-apps.folder');
     try {
         $createdFile = $service->files->insert($file, array('mimeType' => 'application/vnd.google-apps.folder'));
     } catch (Exception $e) {
         $this->_google_drive_cdn->set_error($e->getMessage() . '(wpbgdc: create_folder 1)', false);
         return;
     }
     WPB_Google_Drive_Cdn_Settings::set_setting('folder_id', $createdFile->getId(), 'wpbgdc_folders');
     // set permissions
     $permission = new Google_Service_Drive_Permission();
     $permission->setValue('');
     $permission->setType('anyone');
     $permission->setRole('reader');
     try {
         $service->permissions->insert($createdFile->getId(), $permission);
     } catch (Exception $e) {
         $this->_google_drive_cdn->set_error($e->getMessage() . '(wpbgdc: create_folder 2)', false);
         return;
     }
     try {
         $created_file_info = $service->files->get($createdFile->getId());
     } catch (Exception $e) {
         $this->_google_drive_cdn->set_error($e->getMessage() . '(wpbgdc: create_folder 3)', false);
         return $createdFile->getId();
     }
     WPB_Google_Drive_Cdn_Settings::set_setting('folder_link', $created_file_info->webViewLink, 'wpbgdc_folders');
     WPB_Google_Drive_Cdn_Settings::set_setting('folder_name', $folder, 'wpbgdc_folders');
     return $createdFile->getId();
 }
Beispiel #5
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'];
 }
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();
    }
}
Beispiel #8
0
 public static function send($settings = array(), $files = array(), $send_id = '', $delete_after = false, $delete_remote_after = false)
 {
     global $pb_backupbuddy_destination_errors;
     if ('1' == $settings['disabled']) {
         $pb_backupbuddy_destination_errors[] = __('Error #48933: This destination is currently disabled. Enable it under this destination\'s Advanced Settings.', 'it-l10n-backupbuddy');
         return false;
     }
     if (!is_array($files)) {
         $files = array($files);
     }
     pb_backupbuddy::status('details', 'Google Drive send() function started. Settings: `' . print_r($settings, true) . '`.');
     self::$_timeStart = microtime(true);
     $settings = self::_normalizeSettings($settings);
     if (false === ($settings = self::_connect($settings))) {
         // $settings =
         return self::_error('Error #38923923: Unable to connect with Google Drive. See log for details.');
     }
     $folderID = $settings['folderID'];
     if ('' == $folderID) {
         $folderID = 'root';
     }
     $chunkSizeBytes = $settings['max_burst'] * 1024 * 1024;
     // Send X mb at a time to limit memory usage.
     foreach ($files as $file) {
         // Determine backup type for limiting later.
         $backup_type = '';
         if (stristr($file, '-db-') !== false) {
             $backup_type = 'db';
         } elseif (stristr($file, '-full-') !== false) {
             $backup_type = 'full';
         } elseif (stristr($file, '-files-') !== false) {
             $backup_type = 'files';
         } elseif (stristr($file, '-export-') !== false) {
             $backup_type = 'export';
         }
         if (!file_exists($file)) {
             return self::_error('Error #37792: File selected to send not found: `' . $file . '`.');
         }
         $fileSize = filesize($file);
         $fileinfo = pathinfo($file);
         $fileextension = $fileinfo['extension'];
         if ('zip' == $fileextension) {
             $mimeType = 'application/zip';
         } elseif ('php' == $fileextension) {
             $mimeType = 'application/x-httpd-php';
         } else {
             $mimeType = '';
         }
         pb_backupbuddy::status('details', 'About to upload file `' . $file . '` of size `' . $fileSize . '` with mimetype `' . $mimeType . '` into folder `' . $folderID . '`. Internal chunk size of `' . $chunkSizeBytes . '` bytes.');
         if ($fileSize > $chunkSizeBytes) {
             pb_backupbuddy::status('details', 'File size `' . pb_backupbuddy::$format->file_size($fileSize) . '` exceeds max burst size `' . $settings['max_burst'] . ' MB` so this will be sent in bursts. If time limit nears then send will be chunked across multiple PHP loads.');
             $settings['_chunks_total'] = ceil($fileSize / $chunkSizeBytes);
         }
         if (0 == $settings['_chunks_total']) {
             $settings['_chunks_total'] = 1;
         }
         //Insert a file
         $driveFile = new Google_Service_Drive_DriveFile();
         $driveFile->setTitle(basename($file));
         $driveFile->setDescription('BackupBuddy file');
         $driveFile->setMimeType($mimeType);
         // Set the parent folder.
         if ('root' != $folderID) {
             $parentsCollectionData = new Google_Service_Drive_ParentReference();
             $parentsCollectionData->setId($folderID);
             $driveFile->setParents(array($parentsCollectionData));
         }
         self::$_client->setDefer(true);
         try {
             $insertRequest = self::$_drive->files->insert($driveFile);
         } catch (Exception $e) {
             pb_backupbuddy::alert('Error #3232783268336: initiating upload. Details: ' . $e->getMessage());
             return false;
         }
         // Handle getting resume information to see if resuming is still an option.
         $resumable = false;
         if ('' != $settings['_media_resumeUri']) {
             $headers = array('content-range' => 'bytes */' . $fileSize);
             $request = new Google_Http_Request($settings['_media_resumeUri'], 'PUT', $headers, '');
             $response = self::$_client->getIo()->makeRequest($request);
             if (308 == $response->getResponseHttpCode()) {
                 $range = $response->getResponseHeader('range');
                 if (!empty($range) && preg_match('/bytes=0-(\\d+)$/', $range, $matches)) {
                     $resumable = true;
                     pb_backupbuddy::status('details', 'Last send reported next byte to be `' . $settings['_media_progress'] . '`.');
                     $settings['_media_progress'] = $matches[1] + 1;
                     pb_backupbuddy::status('details', 'Google Drive resuming is available. Google Drive reports next byte to be `' . $settings['_media_progress'] . '`. Range: `' . $range . '`.');
                 }
             }
             if (!$resumable) {
                 pb_backupbuddy::status('details', 'Google Drive could not resume. Too much time may have passed or some other cause.');
             }
             if ($settings['_media_progress'] >= $fileSize) {
                 pb_backupbuddy::status('details', 'Google Drive resuming not needed. Remote file meets or exceeds file size. Completed.');
                 return true;
             }
         }
         // See https://developers.google.com/api-client-library/php/guide/media_upload
         try {
             $media = new Google_Http_MediaFileUpload(self::$_client, $insertRequest, $mimeType, null, true, $chunkSizeBytes);
         } catch (Exception $e) {
             pb_backupbuddy::alert('Error #3893273937: initiating upload. Details: ' . $e->getMessage());
             return;
         }
         $media->setFileSize($fileSize);
         // Reset these internal variables. NOTE: These are by default private. Must modify MediaFileUpload.php to make this possible by setting these vars public. Thanks Google!
         if ('' != $settings['_media_resumeUri']) {
             $media->resumeUri = $settings['_media_resumeUri'];
             $media->progress = $settings['_media_progress'];
         }
         pb_backupbuddy::status('details', 'Opening file for sending in binary mode.');
         $fs = fopen($file, 'rb');
         // If chunked resuming then seek to the correct place in the file.
         if ('' != $settings['_media_progress'] && $settings['_media_progress'] > 0) {
             // Resuming send of a partially transferred file.
             if (0 !== fseek($fs, $settings['_media_progress'])) {
                 // Go off the resume point as given by Google in case it didnt all make it. //$settings['resume_point'] ) ) { // Returns 0 on success.
                 pb_backupbuddy::status('error', 'Error #3872733: Failed to seek file to resume point `' . $settings['_media_progress'] . '` via fseek().');
                 return false;
             }
             $prevPointer = $settings['_media_progress'];
             //$settings['resume_point'];
         } else {
             // New file send.
             $prevPointer = 0;
         }
         $needProcessChunking = false;
         // Set true if we need to spawn off resuming to a new PHP page load.
         $uploadStatus = false;
         while (!$uploadStatus && !feof($fs)) {
             $chunk = fread($fs, $chunkSizeBytes);
             pb_backupbuddy::status('details', 'Chunk of size `' . pb_backupbuddy::$format->file_size($chunkSizeBytes) . '` read into memory. Total bytes summed: `' . ($settings['_media_progress'] + strlen($chunk)) . '` of filesize: `' . $fileSize . '`.');
             pb_backupbuddy::status('details', 'Sending burst file data next. If next message is not "Burst file data sent" then the send likely timed out. Try reducing burst size. Sending now...');
             // Send chunk of data.
             try {
                 $uploadStatus = $media->nextChunk($chunk);
             } catch (Exception $e) {
                 global $pb_backupbuddy_destination_errors;
                 $pb_backupbuddy_destination_errors[] = $e->getMessage();
                 $error = $e->getMessage();
                 pb_backupbuddy::status('error', 'Error #8239832: Error sending burst data. Details: `' . $error . '`.');
                 return false;
             }
             $settings['_chunks_sent']++;
             self::$_chunksSentThisRound++;
             pb_backupbuddy::status('details', 'Burst file data sent.');
             $maxTime = $settings['max_time'];
             if ('' == $maxTime || !is_numeric($maxTime)) {
                 pb_backupbuddy::status('details', 'Max time not set in settings so detecting server max PHP runtime.');
                 $maxTime = backupbuddy_core::detectMaxExecutionTime();
             }
             //return;
             // Handle splitting up across multiple PHP page loads if needed.
             if (!feof($fs) && 0 != $maxTime) {
                 // More data remains so see if we need to consider chunking to a new PHP process.
                 // If we are within X second of reaching maximum PHP runtime then stop here so that it can be picked up in another PHP process...
                 $totalSizeSent = self::$_chunksSentThisRound * $chunkSizeBytes;
                 // Total bytes sent this PHP load.
                 $bytesPerSec = $totalSizeSent / (microtime(true) - self::$_timeStart);
                 $timeRemaining = $maxTime - (microtime(true) - self::$_timeStart + self::TIME_WIGGLE_ROOM);
                 if ($timeRemaining < 0) {
                     $timeRemaining = 0;
                 }
                 $bytesWeCouldSendWithTimeLeft = $bytesPerSec * $timeRemaining;
                 pb_backupbuddy::status('details', 'Total sent: `' . pb_backupbuddy::$format->file_size($totalSizeSent) . '`. Speed (per sec): `' . pb_backupbuddy::$format->file_size($bytesPerSec) . '`. Time Remaining (w/ wiggle): `' . $timeRemaining . '`. Size that could potentially be sent with remaining time: `' . pb_backupbuddy::$format->file_size($bytesWeCouldSendWithTimeLeft) . '` with chunk size of `' . pb_backupbuddy::$format->file_size($chunkSizeBytes) . '`.');
                 if ($bytesWeCouldSendWithTimeLeft < $chunkSizeBytes) {
                     // We can send more than a whole chunk (including wiggle room) so send another bit.
                     pb_backupbuddy::status('message', 'Not enough time left (~`' . $timeRemaining . '`) with max time of `' . $maxTime . '` sec to send another chunk at `' . pb_backupbuddy::$format->file_size($bytesPerSec) . '` / sec. Ran for ' . round(microtime(true) - self::$_timeStart, 3) . ' sec. Proceeding to use chunking.');
                     @fclose($fs);
                     // Tells next chunk where to pick up.
                     if (isset($chunksTotal)) {
                         $settings['_chunks_total'] = $chunksTotal;
                     }
                     // Grab these vars from the class.  Note that we changed these vars from private to public to make chunked resuming possible.
                     $settings['_media_resumeUri'] = $media->resumeUri;
                     $settings['_media_progress'] = $media->progress;
                     // Schedule cron.
                     $cronTime = time();
                     $cronArgs = array($settings, $files, $send_id, $delete_after);
                     $cronHashID = md5($cronTime . serialize($cronArgs));
                     $cronArgs[] = $cronHashID;
                     $schedule_result = backupbuddy_core::schedule_single_event($cronTime, 'destination_send', $cronArgs);
                     if (true === $schedule_result) {
                         pb_backupbuddy::status('details', 'Next Site chunk step cron event scheduled.');
                     } else {
                         pb_backupbuddy::status('error', 'Next Site chunk step cron even FAILED to be scheduled.');
                     }
                     spawn_cron(time() + 150);
                     // Adds > 60 seconds to get around once per minute cron running limit.
                     update_option('_transient_doing_cron', 0);
                     // Prevent cron-blocking for next item.
                     return array($prevPointer, 'Sent part ' . $settings['_chunks_sent'] . ' of ~' . $settings['_chunks_total'] . ' parts.');
                     // filepointer location, elapsed time during the import
                 } else {
                     // End if.
                     pb_backupbuddy::status('details', 'Not approaching limits.');
                 }
             } else {
                 pb_backupbuddy::status('details', 'No more data remains (eg for chunking) so finishing up.');
                 if ('' != $send_id) {
                     require_once pb_backupbuddy::plugin_path() . '/classes/fileoptions.php';
                     $fileoptions_obj = new pb_backupbuddy_fileoptions(backupbuddy_core::getLogDirectory() . 'fileoptions/send-' . $send_id . '.txt', $read_only = false, $ignore_lock = false, $create_file = false);
                     if (true !== ($result = $fileoptions_obj->is_ok())) {
                         pb_backupbuddy::status('error', __('Fatal Error #9034.397237. Unable to access fileoptions data.', 'it-l10n-backupbuddy') . ' Error: ' . $result);
                         return false;
                     }
                     pb_backupbuddy::status('details', 'Fileoptions data loaded.');
                     $fileoptions =& $fileoptions_obj->options;
                     $fileoptions['_multipart_status'] = 'Sent part ' . $settings['_chunks_sent'] . ' of ~' . $settings['_chunks_total'] . ' parts.';
                     $fileoptions['finish_time'] = microtime(true);
                     $fileoptions['status'] = 'success';
                     $fileoptions_obj->save();
                     unset($fileoptions_obj);
                 }
             }
         }
         fclose($fs);
         self::$_client->setDefer(false);
         if (false == $uploadStatus) {
             global $pb_backupbuddy_destination_errors;
             $pb_backupbuddy_destination_errors[] = 'Error #84347474 sending. Details: ' . $uploadStatus;
             return false;
         } else {
             // Success.
             if (true === $delete_remote_after) {
                 self::deleteFile($settings, $uploadStatus->id);
             }
         }
     }
     // end foreach.
     $db_archive_limit = $settings['db_archive_limit'];
     $full_archive_limit = $settings['full_archive_limit'];
     $files_archive_limit = $settings['files_archive_limit'];
     // BEGIN FILE LIMIT PROCESSING. Enforce archive limits if applicable.
     if ($backup_type == 'full') {
         $limit = $full_archive_limit;
     } elseif ($backup_type == 'db') {
         $limit = $db_archive_limit;
     } elseif ($backup_type == 'files') {
         $limit = $files_archive_limit;
     } else {
         $limit = 0;
         pb_backupbuddy::status('warning', 'Warning #34352453244. Google Drive was unable to determine backup type (reported: `' . $backup_type . '`) so archive limits NOT enforced for this backup.');
     }
     pb_backupbuddy::status('details', 'Google Drive database backup archive limit of `' . $limit . '` of type `' . $backup_type . '` based on destination settings.');
     if ($limit > 0) {
         pb_backupbuddy::status('details', 'Google Drive archive limit enforcement beginning.');
         // Get file listing.
         $searchCount = 1;
         $remoteFiles = array();
         while (count($remoteFiles) == 0 && $searchCount < 5) {
             pb_backupbuddy::status('details', 'Checking archive limits. Attempt ' . $searchCount . '.');
             $remoteFiles = pb_backupbuddy_destination_gdrive::listFiles($settings, "title contains 'backup-' AND title contains '-" . $backup_type . "-' AND '" . $folderID . "' IN parents AND trashed=false");
             //"title contains 'backup' and trashed=false" );
             sleep(1);
             $searchCount++;
         }
         // List backups associated with this site by date.
         $backups = array();
         $prefix = backupbuddy_core::backup_prefix();
         foreach ($remoteFiles as $remoteFile) {
             if ('application/vnd.google-apps.folder' == $remoteFile->mimeType) {
                 // Ignore folders.
                 continue;
             }
             if (strpos($remoteFile->originalFilename, 'backup-' . $prefix . '-') !== false) {
                 // Appears to be a backup file for this site.
                 $backups[$remoteFile->id] = strtotime($remoteFile->modifiedDate);
             }
         }
         arsort($backups);
         pb_backupbuddy::status('details', 'Google Drive found `' . count($backups) . '` backups of this type when checking archive limits.');
         if (count($backups) > $limit) {
             pb_backupbuddy::status('details', 'More archives (' . count($backups) . ') than limit (' . $limit . ') allows. Trimming...');
             $i = 0;
             $delete_fail_count = 0;
             foreach ($backups as $buname => $butime) {
                 $i++;
                 if ($i > $limit) {
                     pb_backupbuddy::status('details', 'Trimming excess file `' . $buname . '`...');
                     if (true !== self::deleteFile($settings, $buname)) {
                         pb_backupbuddy::status('details', 'Unable to delete excess Google Drive file `' . $buname . '`. Details: `' . print_r($pb_backupbuddy_destination_errors, true) . '`.');
                         $delete_fail_count++;
                     }
                 }
             }
             pb_backupbuddy::status('details', 'Finished trimming excess backups.');
             if ($delete_fail_count !== 0) {
                 $error_message = 'Google Drive remote limit could not delete ' . $delete_fail_count . ' backups.';
                 pb_backupbuddy::status('error', $error_message);
                 backupbuddy_core::mail_error($error_message);
             }
         }
         pb_backupbuddy::status('details', 'Google Drive completed archive limiting.');
     } else {
         pb_backupbuddy::status('details', 'No Google Drive archive file limit to enforce.');
     }
     // End remote backup limit
     // Made it this far then success.
     return true;
 }
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 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;
        }
    }
 function insertFile($service, $parentId)
 {
     $filename = Request::file('file');
     $kelas = Request::input('kelas');
     $mimeType = $filename->getClientMimeType();
     $title = $kelas . '_' . $filename->getClientOriginalName();
     $description = $filename->getClientMimeType();
     $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, 'mimeType' => $mimeType, 'uploadType' => 'media'));
         // Uncomment the following line to print the File ID
         // print 'File ID: %s' % $createdFile->getId();
         return $createdFile;
     } catch (Exception $e) {
         print "An error occurred: " . $e->getMessage();
     }
 }
Beispiel #12
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;
 }
Beispiel #13
0
 public static function send($settings = array(), $files = array(), $send_id = '', $delete_remote_after = false)
 {
     self::$_timeStart = microtime(true);
     $settings = self::_normalizeSettings($settings);
     if (false === ($settings = self::_connect($settings))) {
         $error = 'Unable to connect with Google Drive. See log for details.';
         echo $error;
         pb_backupbuddy::status('error', $error);
         return false;
     }
     $chunkSizeBytes = $settings['max_burst'] * 1024 * 1024;
     // Send X mb at a time to limit memory usage.
     foreach ($files as $file) {
         $fileSize = filesize($file);
         $fileinfo = pathinfo($file);
         $fileextension = $fileinfo['extension'];
         if ('zip' == $fileextension) {
             $mimeType = 'application/zip';
         } elseif ('php' == $fileextension) {
             $mimeType = 'application/x-httpd-php';
         } else {
             $mimeType = '';
         }
         pb_backupbuddy::status('details', 'About to upload file `' . $file . '` of size `' . $fileSize . '` with mimetype `' . $mimeType . '`. Internal chunk size of `' . $chunkSizeBytes . '` bytes.');
         //Insert a file
         $driveFile = new Google_Service_Drive_DriveFile();
         $driveFile->setTitle(basename($file));
         $driveFile->setDescription('BackupBuddy file');
         $driveFile->setMimeType($mimeType);
         self::$_client->setDefer(true);
         try {
             $insertRequest = self::$_drive->files->insert($driveFile);
         } catch (Exception $e) {
             pb_backupbuddy::alert('Error #3232783268336: initiating upload. Details: ' . $e->getMessage());
             return;
         }
         // See https://developers.google.com/api-client-library/php/guide/media_upload
         try {
             $media = new Google_Http_MediaFileUpload(self::$_client, $insertRequest, $mimeType, null, true, $chunkSizeBytes);
         } catch (Exception $e) {
             pb_backupbuddy::alert('Error #3893273937: initiating upload. Details: ' . $e->getMessage());
             return;
         }
         $media->setFileSize($fileSize);
         pb_backupbuddy::status('details', 'Opening file for sending in binary mode.');
         $fs = fopen($file, 'rb');
         // If chunked resuming then seek to the correct place in the file.
         if ('' != $settings['resume_point'] && $settings['resume_point'] > 0) {
             // Resuming send of a partially transferred file.
             if (0 !== fseek($fs, $settings['resume_point'])) {
                 // Returns 0 on success.
                 pb_backupbuddy::status('error', 'Error #3872733: Failed to seek file to resume point `' . $settings['resume_point'] . '` via fseek().');
                 return false;
             }
             $prevPointer = $settings['resume_point'];
         } else {
             // New file send.
             $prevPointer = 0;
         }
         $needProcessChunking = false;
         // Set true if we need to spawn off resuming to a new PHP page load.
         $uploadStatus = false;
         while (!$uploadStatus && !feof($fs)) {
             $chunk = fread($fs, $chunkSizeBytes);
             $uploadStatus = $media->nextChunk($chunk);
             // Handle splitting up across multiple PHP page loads if needed.
             if (!feof($fs) && 0 != $settings['max_time']) {
                 // More data remains so see if we need to consider chunking to a new PHP process.
                 // If we are within X second of reaching maximum PHP runtime then stop here so that it can be picked up in another PHP process...
                 if (microtime(true) - self::$_timeStart + self::TIME_WIGGLE_ROOM >= $settings['max_time']) {
                     pb_backupbuddy::status('message', 'Approaching limit of available PHP chunking time of `' . $settings['max_time'] . '` sec. Ran for ' . round(microtime(true) - self::$_timeStart, 3) . ' sec. Proceeding to use chunking.');
                     @fclose($fs);
                     // Tells next chunk where to pick up.
                     $settings['resume_point'] = $prevPointer;
                     if (isset($chunksTotal)) {
                         $settings['chunks_total'] = $chunksTotal;
                     }
                     // Schedule cron.
                     $cronTime = time();
                     $cronArgs = array($settings, $files, $send_id, $delete_after = false);
                     $cronHashID = md5($cronTime . serialize($cronArgs));
                     $cronArgs[] = $cronHashID;
                     $schedule_result = backupbuddy_core::schedule_single_event($cronTime, pb_backupbuddy::cron_tag('destination_send'), $cronArgs);
                     if (true === $schedule_result) {
                         pb_backupbuddy::status('details', 'Next Site chunk step cron event scheduled.');
                     } else {
                         pb_backupbuddy::status('error', 'Next Site chunk step cron even FAILED to be scheduled.');
                     }
                     spawn_cron(time() + 150);
                     // Adds > 60 seconds to get around once per minute cron running limit.
                     update_option('_transient_doing_cron', 0);
                     // Prevent cron-blocking for next item.
                     return array($prevPointer, 'Sent part ' . $settings['chunks_sent'] . ' of ~' . $settings['chunks_total'] . ' parts.');
                     // filepointer location, elapsed time during the import
                 } else {
                     // End if.
                     pb_backupbuddy::status('details', 'Not approaching time limit.');
                 }
             } else {
                 pb_backupbuddy::status('details', 'No more data remains (eg for chunking) so finishing up.');
             }
         }
         fclose($fs);
         self::$_client->setDefer(false);
         if (false == $uploadStatus) {
             global $pb_backupbuddy_destination_errors;
             $pb_backupbuddy_destination_errors[] = 'Error #84347474 sending. Details: ' . $uploadStatus;
             return false;
         } else {
             // Success.
             if (true === $delete_remote_after) {
                 self::deleteFile($settings, $uploadStatus->id);
             }
         }
     }
     // end foreach.
     // Made it this far then success.
     return true;
 }
Beispiel #14
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;
 }
/**
 * 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);
    }
}
 /**
  * Upload file to Google drive
  *
  * @param  string $fullPath    Full path to local file being uploaded
  * @param  string $title       File Title
  * @param  string $description File description
  * @return array  $result      Result from Google Drive after upload
  */
 public function store($fullPath, $title, $description)
 {
     $file = new \Google_Service_Drive_DriveFile();
     $file->setTitle($title);
     $file->setDescription($description);
     $file->setMimeType($this->getMimeType($fullPath));
     //set chunks in 1MB
     $chunkSizeBytes = 1 * 1024 * 1024;
     $this->client->setDefer(true);
     $request = $this->service->files->insert($file);
     // Create a media file upload to represent our upload process.
     $media = new \Google_Http_MediaFileUpload($this->client, $request, $this->getMimeType($fullPath), null, true, $chunkSizeBytes);
     $media->setFileSize(filesize($fullPath));
     // Upload the various chunks. $status will be false until the process is complete
     $status = false;
     $handle = fopen($fullPath, "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);
     return $result;
 }
Beispiel #17
0
 /**
  * Upload a file.
  */
 public function actionUpload()
 {
     if (!isset($_FILES['upload'])) {
         throw new CHttpException('400', 'Invalid request.');
     }
     if (isset($_POST['drive']) && $_POST['drive']) {
         // google drive
         $auth = new GoogleAuthenticator();
         if ($auth->getAccessToken()) {
             $service = $auth->getDriveService();
         }
         $createdFile = null;
         if (isset($service, $_SESSION['access_token'], $_FILES['upload'])) {
             try {
                 $file = new Google_Service_Drive_DriveFile();
                 $file->setTitle($_FILES['upload']['name']);
                 $file->setDescription('Uploaded by X2Engine');
                 $file->setMimeType($_FILES['upload']['type']);
                 if (empty($_FILES['upload']['tmp_name'])) {
                     $err = false;
                     switch ($_FILES['newfile']['error']) {
                         case UPLOAD_ERR_INI_SIZE:
                         case UPLOAD_ERR_FORM_SIZE:
                             $err .= 'File size exceeds limit of ' . get_max_upload() . ' bytes.';
                             break;
                         case UPLOAD_ERR_PARTIAL:
                             $err .= 'File upload was not completed.';
                             break;
                         case UPLOAD_ERR_NO_FILE:
                             $err .= 'Zero-length file uploaded.';
                             break;
                         default:
                             $err .= 'Internal error ' . $_FILES['newfile']['error'];
                             break;
                     }
                     if ((bool) $message) {
                         throw new CException($message);
                     }
                 }
                 $data = file_get_contents($_FILES['upload']['tmp_name']);
                 $createdFile = $service->files->insert($file, array('data' => $data, 'mimeType' => $_FILES['upload']['type'], 'uploadType' => 'multipart'));
                 if ($createdFile instanceof Google_Service_Drive_DriveFile) {
                     $model = new Media();
                     $model->fileName = $createdFile['id'];
                     $model->name = $createdFile['title'];
                     if (isset($_POST['associationId'])) {
                         $model->associationId = $_POST['associationId'];
                     }
                     if (isset($_POST['associationType'])) {
                         $model->associationType = $_POST['associationType'];
                     }
                     if (isset($_POST['private'])) {
                         $model->private = $_POST['private'];
                     }
                     $model->uploadedBy = Yii::app()->user->getName();
                     $model->mimetype = $createdFile['mimeType'];
                     $model->filesize = $createdFile['fileSize'];
                     $model->drive = 1;
                     $model->save();
                     if ($model->associationType == 'feed') {
                         $event = new Events();
                         $event->user = Yii::app()->user->getName();
                         if (isset($_POST['attachmentText']) && !empty($_POST['attachmentText'])) {
                             $event->text = $_POST['attachmentText'];
                         } else {
                             $event->text = Yii::t('app', 'Attached file: ');
                         }
                         $event->type = 'media';
                         $event->timestamp = time();
                         $event->lastUpdated = time();
                         $event->associationId = $model->id;
                         $event->associationType = 'Media';
                         $event->save();
                         if (Auxlib::isAjax()) {
                             return print "success";
                         }
                         $this->redirect(array('/profile/view', 'id' => Yii::app()->user->getId()));
                     } elseif ($model->associationType == 'docs') {
                         if (Auxlib::isAjax()) {
                             return print "success";
                         }
                         $this->redirect(array('/docs/docs/index'));
                     } elseif (!empty($model->associationType) && !empty($model->associationId)) {
                         $note = new Actions();
                         $note->createDate = time();
                         $note->dueDate = time();
                         $note->completeDate = time();
                         $note->complete = 'Yes';
                         $note->visibility = '1';
                         $note->completedBy = Yii::app()->user->getName();
                         if ($model->private) {
                             $note->assignedTo = Yii::app()->user->getName();
                             $note->visibility = '0';
                         } else {
                             $note->assignedTo = 'Anyone';
                         }
                         $note->type = 'attachment';
                         $note->associationId = $_POST['associationId'];
                         $note->associationType = $_POST['associationType'];
                         $association = $this->getAssociation($note->associationType, $note->associationId);
                         if ($association != null) {
                             $note->associationName = $association->name;
                         }
                         $note->actionDescription = $model->fileName . ':' . $model->id;
                         if ($note->save()) {
                             if (Auxlib::isAjax()) {
                                 return print "success";
                             }
                             $this->redirect(array($model->associationType . '/' . $model->associationId));
                         }
                     } else {
                         if (Auxlib::isAjax()) {
                             return print "success";
                         }
                         $this->redirect('/media/media/view', array('id' => $model->id));
                     }
                 } else {
                     throw new CHttpException('400', 'Invalid request.');
                 }
             } catch (Google_Auth_Exception $e) {
                 $auth->flushCredentials();
                 $auth->setErrors($e->getMessage());
                 $service = null;
                 $createdFile = null;
             }
         } else {
             if (isset($_SERVER['HTTP_REFERER'])) {
                 if (Auxlib::isAjax()) {
                     return print "success";
                 }
                 $this->redirect($_SERVER['HTTP_REFERER']);
             } else {
                 throw new CHttpException('400', 'Invalid request');
             }
         }
     } else {
         // non-google drive upload
         $model = new Media();
         $temp = CUploadedFile::getInstanceByName('upload');
         // file uploaded through form
         if ($temp && ($tempName = $temp->getTempName()) && !empty($tempName)) {
             $name = $temp->getName();
             $name = str_replace(' ', '_', $name);
             $model->fileName = $name;
             $model->resolveNameConflicts();
             $username = Yii::app()->user->name;
             // copy file to user's media uploads directory
             if (FileUtil::ccopy($tempName, "uploads/protected/media/{$username}/{$model->fileName}")) {
                 if (isset($_POST['associationId'])) {
                     $model->associationId = $_POST['associationId'];
                 }
                 if (isset($_POST['associationType'])) {
                     $model->associationType = $_POST['associationType'];
                 }
                 if (isset($_POST['private'])) {
                     $model->private = true;
                 }
                 $model->uploadedBy = Yii::app()->user->getName();
                 $model->createDate = time();
                 $model->lastUpdated = time();
                 $model->mimetype = $temp->type;
                 if (!$model->save()) {
                     $errors = $model->getErrors();
                     $error = ArrayUtil::pop(ArrayUtil::pop($errors));
                     Yii::app()->user->setFlash('top-error', Yii::t('app', 'Attachment failed. ' . $error));
                     if (Auxlib::isAjax()) {
                         return print "success";
                     }
                     $this->redirect(array($model->associationType . '/' . $model->associationType . '/view', 'id' => $model->associationId));
                     Yii::app()->end();
                 } else {
                     $relatedModel = X2Model::getModelOfTypeWithId($model->associationType, $model->associationId, true);
                     $model->createRelationship($relatedModel);
                 }
                 // handle different upload types
                 switch ($model->associationType) {
                     case 'feed':
                         $this->handleFeedTypeUpload($model, $name);
                         break;
                     case 'docs':
                         if (Auxlib::isAjax()) {
                             return print "success";
                         }
                         $this->redirect(array('/docs/docs/index'));
                         break;
                     case 'loginSound':
                     case 'notificationSound':
                         if (Auxlib::isAjax()) {
                             return print "success";
                         }
                         $this->redirect(array('/profile/settings', 'id' => Yii::app()->user->getId()));
                         break;
                     case 'bg':
                     case 'bg-private':
                         $this->redirect(array('/profile/settings', 'bgId' => $model->id));
                         break;
                     case 'none':
                         if (Auxlib::isAjax()) {
                             return print "success";
                         }
                         break;
                     case 'topicReply':
                         $this->handleTopicReplyUpload($model, $name);
                         break;
                     default:
                         $this->handleDefaultUpload($model, $name);
                         break;
                 }
             }
         } else {
             if (isset($_SERVER['HTTP_REFERER'])) {
                 if (Auxlib::isAjax()) {
                     return print "success";
                 }
                 $this->redirect($_SERVER['HTTP_REFERER']);
             } else {
                 throw new CHttpException('400', 'Invalid request');
             }
         }
         if (isset($_GET['redirect'])) {
             $this->redirect($_SERVER['HTTP_REFERER']);
         }
     }
 }
/**
 * 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;
}
Beispiel #19
0
 public function uploadDoc($bean, $fileToUpload, $docName, $mimeType)
 {
     $client = $this->getClient();
     $service = new Google_Service_Drive($client);
     $file = new Google_Service_Drive_DriveFile($client);
     $file->setTitle($docName);
     $file->setDescription($bean->description);
     try {
         $createdFile = $service->files->insert($file, array('data' => file_get_contents($fileToUpload), 'uploadType' => 'multipart'));
     } catch (Google_Exception $e) {
         return array('success' => false, 'errorMessage' => $GLOBALS['app_strings']['ERR_EXTERNAL_API_SAVE_FAIL']);
     }
     $bean->doc_id = $createdFile->id;
     $bean->doc_url = $createdFile->alternateLink;
     return array('success' => true);
 }
Beispiel #20
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();
    }
}
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;
}
Beispiel #22
0
 /**
  * Upload a file
  * @param string $fileName
  * @param string $fileLocation
  * @param \Google_Service_Drive_DriveFile $folder
  * @param string $uploadType
  * @return \Google_Service_Drive_DriveFile
  */
 public function uploadFile($fileName, $fileLocation, \Google_Service_Drive_DriveFile $folder = null, $uploadType = 'media')
 {
     //Insert a file
     $file = new \Google_Service_Drive_DriveFile();
     $file->setTitle($fileName);
     $fileInfo = new \finfo(FILEINFO_MIME_TYPE);
     $mimeType = $fileInfo->file($fileLocation);
     $file->setDescription($fileName);
     $file->setMimeType($mimeType);
     if ($folder !== null) {
         $parent = new \Google_Service_Drive_ParentReference();
         $parent->setId($folder->getId());
         $file->setParents(array($parent));
     }
     $data = file_get_contents($fileLocation);
     try {
         return $this->service->files->insert($file, array('data' => $data, 'mimeType' => $file->getMimeType(), 'uploadType' => $uploadType));
     } catch (\Google_Service_Exception $obj_ex) {
         $this->service->getClient()->getLogger()->error($obj_ex->getMessage());
         return false;
     }
 }
Beispiel #23
0
 <?php 
require_once 'vendor/google/apiclient/src/Google/Client.php';
require_once 'vendor/google/apiclient/src/Google/Service/Drive.php';
$client = new Google_Client();
$client->setClientId('<YOUR_CLIENT_ID>');
$client->setClientSecret('<YOUR_CLIENT_SECRET>');
$client->setRedirectUri('<YOUR_REGISTERED_REDIRECT_URI>');
$client->setScopes(array('https://www.googleapis.com/auth/drive.file'));
$session_start();
if (isset($_GET['code']) || isset($_SESSION['access_token']) && $_SESSION['access_token']) {
    if (isset($_GET['code'])) {
        $client->authenticate($_GET['code']);
        $_SESSION['access_token'] = $client->getAccessToken();
    } else {
        $client->setAccessToken($_SESSION['access_token']);
    }
    $service = new Google_Service_Drive($client);
    $file = new Google_Service_Drive_DriveFile();
    $file->setTitle('image.jpg');
    $file->setDescription('image');
    $file->setMimeType('image/jpeg');
    $data = file_get_contents('image.jpg');
    $createdFile = $service->files->insert($file, array('data' => $data, 'mimeType' => 'image/jpeg', 'uploadType' => 'multipart'));
    print_r($createdFile);
} else {
    $authUrl = $client->createAuthUrl();
    header('Location: ' . $authUrl);
    exit;
}
 private static function getFolder($access_token, $config)
 {
     $client = self::getGoogleClient($config);
     $client->setAccessToken($access_token);
     $service = new \Google_Service_Drive($client);
     $parameters['q'] = "mimeType='application/vnd.google-apps.folder' and 'root' in parents and trashed=false";
     try {
         $data = $service->files->listFiles($parameters);
     } catch (\Exception $e) {
         return array('status' => 'error');
     }
     $files = $data->getItems();
     foreach ($files as $file) {
         if ($file['title'] == 'PDFFiller') {
             return array('status' => 'ok', 'id' => $file['id']);
         }
     }
     $file = new \Google_Service_Drive_DriveFile();
     $file->setTitle('PDFFiller');
     //name of the folder
     $file->setDescription('PDFFiller uploads');
     $file->setMimeType('application/vnd.google-apps.folder');
     $createdFile = $service->files->insert($file, array('mimeType' => 'application/vnd.google-apps.folder'));
     return array('status' => 'ok', 'id' => $createdFile->id);
 }
 public  function insertFile($service, $title, $description, $parentId, $mimeType, $filedata) {
     $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 {
         $createdFile = $service->files->insert($file, array(
             'data' =>$filedata,
             'mimeType' =>'application/vnd.openxmlformats-officedocument.wordprocessingml.document',//$mimeType,
             'uploadType'=>'media'
         ));
         return $createdFile->getId();//$createdFile->getId();
     } catch (Exception $e) {
         return 0;
     }
 }