/**
  * Create new file and write into it from file pointer.
  * Return new file path or false on error.
  *
  * @param resource $fp   file pointer
  * @param string   $dir  target dir path
  * @param string   $name file name
  * @param array    $stat file stat (required by some virtual fs)
  *
  * @return bool|string
  *
  * @author Dmitry (dio) Levashov
  **/
 protected function _save($fp, $path, $name, $stat)
 {
     if ($name !== '') {
         $path .= '/' . $name;
     }
     list($parentId, $itemId, $parent) = $this->_gd_splitPath($path);
     if ($name === '') {
         $stat['iid'] = $itemId;
     }
     if (!$stat || empty($stat['iid'])) {
         $opts = ['q' => sprintf('trashed=false and "%s" in parents and name="%s"', $parentId, $name), 'fields' => self::FETCHFIELDS_LIST];
         $srcFile = $this->_gd_query($opts);
         $srcFile = empty($srcFile) ? null : $srcFile[0];
     } else {
         $srcFile = $this->_gd_getFile($path);
     }
     try {
         $mode = 'update';
         $mime = isset($stat['mime']) ? $stat['mime'] : '';
         $file = new Google_Service_Drive_DriveFile();
         if ($srcFile) {
             $mime = $srcFile->getMimeType();
         } else {
             $mode = 'insert';
             $file->setName($name);
             $file->setParents([$parentId]);
         }
         if (!$mime) {
             $mime = self::mimetypeInternalDetect($name);
         }
         if ($mime === 'unknown') {
             $mime = 'application/octet-stream';
         }
         $file->setMimeType($mime);
         $size = 0;
         if (isset($stat['size'])) {
             $size = $stat['size'];
         } else {
             $fstat = fstat($fp);
             if (!empty($fstat['size'])) {
                 $size = $fstat['size'];
             }
         }
         // set chunk size (max: 100MB)
         $chunkSizeBytes = 100 * 1024 * 1024;
         if ($size > 0) {
             $memory = elFinder::getIniBytes('memory_limit');
             if ($memory) {
                 $chunkSizeBytes = min([$chunkSizeBytes, intval($memory / 4 / 256) * 256]);
             }
         }
         if ($size > $chunkSizeBytes) {
             $client = $this->client;
             // Call the API with the media upload, defer so it doesn't immediately return.
             $client->setDefer(true);
             if ($mode === 'insert') {
                 $request = $this->service->files->create($file, ['fields' => self::FETCHFIELDS_GET]);
             } else {
                 $request = $this->service->files->update($srcFile->getId(), $file, ['fields' => self::FETCHFIELDS_GET]);
             }
             // Create a media file upload to represent our upload process.
             $media = new Google_Http_MediaFileUpload($client, $request, $mime, null, true, $chunkSizeBytes);
             $media->setFileSize($size);
             // Upload the various chunks. $status will be false until the process is
             // complete.
             $status = false;
             while (!$status && !feof($fp)) {
                 elFinder::extendTimeLimit();
                 // read until you get $chunkSizeBytes from TESTFILE
                 // fread will never return more than 8192 bytes if the stream is read buffered and it does not represent a plain file
                 // An example of a read buffered file is when reading from a URL
                 $chunk = $this->_gd_readFileChunk($fp, $chunkSizeBytes);
                 $status = $media->nextChunk($chunk);
             }
             // The final value of $status will be the data from the API for the object
             // that has been uploaded.
             if ($status !== false) {
                 $obj = $status;
             }
             $client->setDefer(false);
         } else {
             $params = ['data' => stream_get_contents($fp), 'uploadType' => 'media', 'fields' => self::FETCHFIELDS_GET];
             if ($mode === 'insert') {
                 $obj = $this->service->files->create($file, $params);
             } else {
                 $obj = $this->service->files->update($srcFile->getId(), $file, $params);
             }
         }
         if ($obj instanceof Google_Service_Drive_DriveFile) {
             return $this->_joinPath($parent, $obj->getId());
         } else {
             return false;
         }
     } catch (Exception $e) {
         return $this->setError('GoogleDrive error: ' . $e->getMessage());
     }
 }
 public function testResultCode()
 {
     $client = $this->getClient();
     $request = new Google_Http_Request('http://www.example.com', 'POST');
     // Test resumable upload
     $media = new Google_Http_MediaFileUpload($client, $request, 'image/png', 'a', true);
     $this->assertEquals(null, $media->getHttpResultCode());
 }
Exemplo n.º 3
0
 /**
  * Upload Video.
  *
  * @param \Userdesk\Submission\Classes\SubmissionVideoItem $item;
  *
  * @return \Userdesk\Submission\Classes\SubmissionResult;
  */
 public function uploadVideo(SubmissionVideoItem $item)
 {
     $google = $this->providerFromToken($this->token);
     try {
         $youtube = new \Google_Service_YouTube($google);
         $videoPath = $item->getVideo();
         if (!empty($videoPath)) {
             // Create a snipet with title, description, tags and category id
             $snippet = new \Google_Service_YouTube_VideoSnippet();
             $snippet->setTitle($item->getTitle());
             $snippet->setDescription($item->getDescription());
             $snippet->setTags(explode(',', $item->getKeywords()));
             // Numeric video category. See
             // https://developers.google.com/youtube/v3/docs/videoCategories/list
             $snippet->setCategoryId("22");
             $status = new \Google_Service_YouTube_VideoStatus();
             $status->privacyStatus = "public";
             // Create a YouTube video with snippet and status
             $video = new \Google_Service_YouTube_Video();
             $video->setSnippet($snippet);
             $video->setStatus($status);
             // Size of each chunk of data in bytes. Setting it higher leads faster upload (less chunks,
             // for reliable connections). Setting it lower leads better recovery (fine-grained chunks)
             $chunkSizeBytes = 1 * 1024 * 1024;
             $google->setDefer(true);
             $insertRequest = $youtube->videos->insert("status,snippet", $video);
             // Create a MediaFileUpload with resumable uploads
             $media = new \Google_Http_MediaFileUpload($google, $insertRequest, 'video/*', null, true, $chunkSizeBytes);
             $media->setFileSize(filesize($videoPath));
             // Create a video insert request
             $uploadStatus = false;
             // Read file and upload chunk by chunk
             $handle = fopen($videoPath, "rb");
             while (!$uploadStatus && !feof($handle)) {
                 $chunk = fread($handle, $chunkSizeBytes);
                 $uploadStatus = $media->nextChunk($chunk);
             }
             fclose($handle);
             $google->setDefer(false);
             if (!empty($uploadStatus) && !empty($uploadStatus->id)) {
                 $url = "http://www.youtube.com/watch?v=" . $uploadStatus->id;
                 return new SubmissionResult(true, '', $url);
             }
             return new SubmissionResult(false, 'Video Upload Failed');
         }
     } catch (\Google_ServiceException $e) {
         throw new InvalidUploadException($e->getMessage());
     } catch (\Google_Exception $e) {
         throw new InvalidUploadException($e->getMessage());
     } catch (Exception $e) {
         throw new InvalidUploadException($e->getMessage());
     }
 }
 public function testGetUploadType()
 {
     $client = $this->getClient();
     $request = new Google_Http_Request('http://www.example.com', 'POST');
     // Test resumable upload
     $media = new Google_Http_MediaFileUpload($client, $request, 'image/png', 'a', true);
     $params = array('mediaUpload' => array('value' => $media));
     $this->assertEquals('resumable', $media->getUploadType(null));
     // Test data *only* uploads
     $media = new Google_Http_MediaFileUpload($client, $request, 'image/png', 'a', false);
     $this->assertEquals('media', $media->getUploadType(null));
     // Test multipart uploads
     $media = new Google_Http_MediaFileUpload($client, $request, 'image/png', 'a', false);
     $this->assertEquals('multipart', $media->getUploadType(array('a' => 'b')));
 }
 public function media_file_upload($_bucket = null, $_file = null, $_name = null)
 {
     # init
     $result = new stdClass();
     $result->error = null;
     $result->status = null;
     $result->exception = null;
     # timer
     $result->starttime = microtime();
     # init gcs api
     $gso = new Google_Service_Storage_StorageObject();
     $gso->setName($_name);
     $gso->setBucket($_bucket);
     $finfo = finfo_open(FILEINFO_MIME_TYPE);
     $mimetype = finfo_file($finfo, $_file);
     $chunkSizeBytes = 1 * 1024 * 1024;
     $this->client->setDefer(true);
     $filetoupload = array('name' => $_name, 'uploadType' => 'resumable');
     # service
     $this->newStorageService();
     $status = false;
     # try
     try {
         $request = $this->storageService->objects->insert($_bucket, $gso, $filetoupload);
         $media = new Google_Http_MediaFileUpload($this->client, $request, $mimetype, null, true, $chunkSizeBytes);
         $media->setFileSize(filesize($_file));
         $handle = fopen($_file, "rb");
         # loop chunks
         while (!$status && !feof($handle)) {
             $chunk = fread($handle, $chunkSizeBytes);
             $status = $media->nextChunk($chunk);
         }
         fclose($handle);
         $this->client->setDefer(false);
         $result->status = $status;
     } catch (Exception $e) {
         $result->error = true;
         $result->status = 'GCS upload failed';
         $result->exception = $e;
     }
     # timer
     $result->endtime = microtime();
     $result->totaltime = $this->get_totaltime($result);
     # verify response
     $result->httpcode = http_response_code();
     $result->error = isset($status->kind) && $status->kind == self::STORAGE_OBJECT ? false : true;
     return $result;
 }
Exemplo n.º 6
0
function uploadVideo($season, $episode)
{
    global $youtube;
    // Check to ensure that the access token was successfully acquired.
    if ($client->getAccessToken()) {
        try {
            // XXX pick file name
            $videoPath = "/path/to/file.mp4";
            $snippet = new Google_Service_YouTube_VideoSnippet();
            $snippet->setTitle('SteamLUG Cast s03e00 ‐');
            // XXX capture from youtube description
            $snippet->setDescription('Test description');
            // TODO licence? comments? language? can we leave these as default?
            $snippet->setTags(array('linux', 'gaming', 'steam', 'steamlug', 'lug', 'podcast', 'steamlugcast', 'gaming on linux', 'steam for linux', 'linux steam', 'linux games', 'gaming on fedora', 'steam for fedora', 'fedora steam', 'fedora games', 'gaming on ubuntu', 'steam for ubuntu', 'ubuntu steam', 'ubuntu games', 'gaming on arch', 'steam for arch', 'arch steam', 'arch games'));
            // https://developers.google.com/youtube/v3/docs/videoCategories/list#try-it using ‘snippet’ and ‘GB’
            $snippet->setCategoryId('20');
            $status = new Google_Service_YouTube_VideoStatus();
            $status->privacyStatus = 'unlisted';
            $video = new Google_Service_YouTube_Video();
            $video->setSnippet($snippet);
            $video->setStatus($status);
            $chunkSizeBytes = 2 * 1024 * 1024;
            $client->setDefer(true);
            $insertRequest = $youtube->videos->insert("status,snippet", $video);
            $media = new Google_Http_MediaFileUpload($client, $insertRequest, 'video/*', null, true, $chunkSizeBytes);
            $media->setFileSize(filesize($videoPath));
            // Read the media file and upload it chunk by chunk.
            $status = false;
            $handle = fopen($videoPath, 'rb');
            while (!$status && !feof($handle)) {
                $chunk = fread($handle, $chunkSizeBytes);
                $status = $media->nextChunk($chunk);
            }
            fclose($handle);
            // If you want to make other calls after the file upload, set setDefer back to false
            $client->setDefer(false);
            // good!
        } catch (Google_ServiceException $e) {
            // ' A service error occurred: '. htmlspecialchars( $e->getMessage( ) )
        } catch (Google_Exception $e) {
            // 'An client error occurred: ' . htmlspecialchars( $e->getMessage( ) )
        }
    } else {
        // 'We’re missing an access token'
        // TODO something here :^)
    }
}
Exemplo n.º 7
0
function doResumableUpload(Google_Client $client)
{
    // Drive service
    $driveService = new Google_Service_Drive($client);
    $gs_basepath = 'gs://' . CloudStorageTools::getDefaultGoogleStorageBucketName();
    $fileName = UPLOAD_FILENAME;
    // 82.52MB file
    $fileToUploadPath = $gs_basepath . "/{$fileName}";
    $uploadFilesize = filesize($fileToUploadPath);
    $options = array('gs' => array('enable_cache' => false, 'acl' => 'public-read'));
    $ctx = stream_context_create($options);
    if (($handle = fopen($fileToUploadPath, 'r', false, $ctx)) === false) {
        throw new Exception('fopen failed.');
    }
    $mimeType = CloudStorageTools::getContentType($handle);
    // prepare a drive file
    $file = new Google_Service_Drive_DriveFile();
    $file->setTitle($fileName);
    $file->setMimeType($mimeType);
    $file->setFileSize($uploadFilesize);
    // You can also set the parent folder:
    // @see https://developers.google.com/drive/v2/reference/files/insert
    $chunkSizeBytes = 256 * 1024 * 4 * 1;
    // upload in multiples of 256K (1M * n)
    // Call the API with the media upload, defer so it doesn't immediately return.
    $client->setDefer(true);
    $request = $driveService->files->insert($file);
    // Create a media file upload to represent our upload process.
    $media = new Google_Http_MediaFileUpload($client, $request, $mimeType, null, true, $chunkSizeBytes);
    // set the media filesize to the actual filesize.
    $media->setFileSize($uploadFilesize);
    // Upload the various chunks. $status will be false until the process is complete.
    $status = false;
    while (!$status && !feof($handle)) {
        $chunk = readChunk($handle, $chunkSizeBytes);
        $status = $media->nextChunk($chunk);
    }
    fclose($handle);
    // Reset to the client to execute requests immediately in the future.
    $client->setDefer(false);
    var_dump($status);
}
Exemplo n.º 8
0
 function uploadFile()
 {
     $cachedfolder = $this->cache->isCached($this->_requestedEntry);
     if ($cachedfolder === false) {
         $cachedfolder = $this->getEntry($this->_requestedEntry);
         if ($cachedfolder === false) {
             return new WP_Error('broke', __("Root folder not found ", 'useyourdrive'));
             die;
         }
     }
     /* Check if user is allowed to upload to this dir */
     if (!$cachedfolder->isInFolder($this->_rootFolder)) {
         return new WP_Error('broke', __("You are not authorized to upload files to this directory", 'useyourdrive'));
         die;
     }
     /* Upload File to server */
     require 'jquery-file-upload/server/UploadHandler.php';
     $accept_file_types = '/.(' . $this->options['upload_ext'] . ')$/i';
     $max_file_size = $this->options['maxfilesize'];
     $uploadir = wp_upload_dir();
     $options = array('upload_dir' => $uploadir['path'] . '/', 'upload_url' => $uploadir['url'] . '/', 'access_control_allow_methods' => array('POST', 'PUT'), 'accept_file_types' => $accept_file_types, 'inline_file_types' => '/\\.____$/i', 'orient_image' => false, 'image_versions' => array(), 'max_file_size' => $max_file_size, 'print_response' => false);
     if ($this->options['demo'] === '1') {
         $options['accept_file_types'] = '/\\.____$/i';
     }
     $error_messages = array(1 => __('The uploaded file exceeds the upload_max_filesize directive in php.ini', 'useyourdrive'), 2 => __('The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form', 'useyourdrive'), 3 => __('The uploaded file was only partially uploaded', 'useyourdrive'), 4 => __('No file was uploaded', 'useyourdrive'), 6 => __('Missing a temporary folder', 'useyourdrive'), 7 => __('Failed to write file to disk', 'useyourdrive'), 8 => __('A PHP extension stopped the file upload', 'useyourdrive'), 'post_max_size' => __('The uploaded file exceeds the post_max_size directive in php.ini', 'useyourdrive'), 'max_file_size' => __('File is too big', 'useyourdrive'), 'min_file_size' => __('File is too small', 'useyourdrive'), 'accept_file_types' => __('Filetype not allowed', 'useyourdrive'), 'max_number_of_files' => __('Maximum number of files exceeded', 'useyourdrive'), 'max_width' => __('Image exceeds maximum width', 'useyourdrive'), 'min_width' => __('Image requires a minimum width', 'useyourdrive'), 'max_height' => __('Image exceeds maximum height', 'useyourdrive'), 'min_height' => __('Image requires a minimum height', 'useyourdrive'));
     $this->upload_handler = new UploadHandler($options, false, $error_messages);
     $response = @$this->upload_handler->post(false);
     /* Upload files to Google Drive */
     foreach ($response['files'] as &$file) {
         /* Check user permission */
         $userrole = $cachedfolder->getItem()->getUserPermission()->getRole();
         if (in_array($userrole, array('reader', 'commenter'))) {
             $file->error = __("You are not authorized to upload files to this directory", 'useyourdrive');
         }
         if (!isset($file->error)) {
             /* Write file */
             $filePath = $file->tmp_path;
             $chunkSizeBytes = 1 * 1024 * 1024;
             /* Update Mime-type if needed (for IE8 and lower?) */
             include_once 'mime-types/mime-types.php';
             $fileExtension = pathinfo($file->name, PATHINFO_EXTENSION);
             $file->type = getMimeType($fileExtension);
             try {
                 /* Create new Google File */
                 $googledrive_file = new Google_Service_Drive_DriveFile();
                 $googledrive_file->setTitle($file->name);
                 $googledrive_file->setMimeType($file->type);
                 /* Add Parent to Google File */
                 if ($this->_lastFolder != null) {
                     $parent = new Google_Service_Drive_ParentReference();
                     $parent->setId($this->_lastFolder);
                     $googledrive_file->setParents(array($parent));
                 }
                 /* Call the API with the media upload, defer so it doesn't immediately return. */
                 $this->client->setDefer(true);
                 $convert = $this->options['convert'] === '1' ? true : false;
                 $request = $this->googleDriveService->files->insert($googledrive_file, array('convert' => $convert));
                 $request->disableGzip();
                 /* Create a media file upload to represent our upload process. */
                 $media = new Google_Http_MediaFileUpload($this->client, $request, $file->type, null, true, $chunkSizeBytes);
                 $media->setFileSize(filesize($filePath));
                 /* Start partialy upload 
                    Upload the various chunks. $status will be false until the process is
                    complete. */
                 $status = false;
                 $handle = fopen($filePath, "rb");
                 while (!$status && !feof($handle)) {
                     set_time_limit(60);
                     $chunk = fread($handle, $chunkSizeBytes);
                     $uploadStatus = $media->nextChunk($chunk);
                 }
                 fclose($handle);
             } catch (Exception $ex) {
                 $file->error = __('Not uploaded to Google Drive', 'useyourdrive') . ': ' . $ex->getMessage();
             }
             $this->client->setDefer(false);
             if (!empty($uploadStatus)) {
                 /* check if uploaded file has size */
                 $newentry = $this->googleDriveService->files->get($uploadStatus['id'], array("userIp" => $this->userip));
                 if ($newentry->getFileSize() === 0 && strpos($newentry->getMimeType(), 'google-apps') === false) {
                     $deletedentry = $this->googleDriveService->files->delete($newentry->getId(), array("userIp" => $this->userip));
                     $file->error = __('Not succesfully uploaded to Google Drive', 'useyourdrive');
                 } else {
                     /* Add new file to our Cache */
                     $cachedentry = $this->cache->addToCache($newentry);
                     $file->completepath = $cachedentry->getPath($this->_rootFolder);
                     $file->fileid = $newentry->getId();
                     $file->filesize = UseyourDrive_bytesToSize1024($file->size);
                     $file->link = urlencode($newentry->getAlternateLink());
                 }
             }
         } else {
             if ($this->options['debug'] === '1') {
                 $file->error = __('Uploading failed', 'useyourdrive') . ': ' . $file->error;
             } else {
                 $file->error = __('Uploading failed', 'useyourdrive');
             }
         }
     }
     /* Send email if needed */
     if ($this->options['notificationupload'] === '1') {
         $this->sendNotificationEmail('upload', $response['files']);
     }
     /* Create response */
     $this->upload_handler->generate_response($response);
     die;
 }
 protected function submitCaption(Google_Service_YouTube $youtube, KalturaYouTubeApiCaptionDistributionInfo $captionInfo, $remoteId)
 {
     if (!file_exists($captionInfo->filePath)) {
         throw new KalturaDistributionException("The caption file [{$captionInfo->filePath}] was not found (probably not synced yet), the job will retry");
     }
     $captionSnippet = new Google_Service_YouTube_CaptionSnippet();
     $captionSnippet->setVideoId($remoteId);
     $captionSnippet->setLanguage($captionInfo->language);
     $captionSnippet->setName($captionInfo->label);
     $caption = new Google_Service_YouTube_Caption();
     $caption->setSnippet($captionSnippet);
     $chunkSizeBytes = 1 * 1024 * 1024;
     $youtube->getClient()->setDefer(true);
     $insertRequest = $youtube->captions->insert('snippet', $caption);
     $media = new Google_Http_MediaFileUpload($youtube->getClient(), $insertRequest, '*/*', null, true, $chunkSizeBytes);
     $media->setFileSize(filesize($captionInfo->filePath));
     $ingestedCaption = false;
     $handle = fopen($captionInfo->filePath, "rb");
     while (!$ingestedCaption && !feof($handle)) {
         $chunk = fread($handle, $chunkSizeBytes);
         $ingestedCaption = $media->nextChunk($chunk);
     }
     fclose($handle);
     $youtube->getClient()->setDefer(false);
     $remoteMediaFile = new KalturaDistributionRemoteMediaFile();
     $remoteMediaFile->remoteId = $ingestedCaption['id'];
     $remoteMediaFile->version = $captionInfo->version;
     $remoteMediaFile->assetId = $captionInfo->assetId;
     return $remoteMediaFile;
 }
/**
 *	Upload the video files to youtube
 *	No matter success or fail, the result will be logged in logStatus()
 * 	@param String $videoPath 		Local video path (./1.mp4)
 *	@param String $videoTitle 		Video Title
 *	@param String $videoDescription Video Description, allow \n characters and links
 *	@param int 	  $videoCategory	Video Category ID, Please refer to the list - https://gist.github.com/dgp/1b24bf2961521bd75d6c
 *	@param String[] $videoTags		Keyword Tags array
 */
function uploadYoutube($videoPath, $videoTitle, $videoDescription, $videoCategory, $videoTags)
{
    $OAUTH2_CLIENT_ID = 'XXX.apps.googleusercontent.com';
    //TODO: UPDATE YOUR CLIENT ID
    $OAUTH2_CLIENT_SECRET = 'XXX';
    //TODO:UPDATE YOUR CLIENT SECRET
    $RESULT = array('refreshToken' => 'XXXXXXXXXXXXX');
    //TODO:UPDATE YOUR PROPOSED ACCOUNT REFRESH ID
    $client = new Google_Client();
    $client->setClientId($OAUTH2_CLIENT_ID);
    $client->setClientSecret($OAUTH2_CLIENT_SECRET);
    $client->setScopes('https://www.googleapis.com/auth/youtube');
    $redirect = filter_var('http://localhost/authorize/');
    $client->setRedirectUri($redirect);
    $youtube = new Google_Service_YouTube($client);
    $client->refreshToken($RESULT['refreshToken']);
    $RESULT['accessToken'] = $client->getAccessToken()['access_token'];
    $client->authenticate($RESULT['accessToken']);
    if ($client->getAccessToken()) {
        try {
            logStatus('Video Start Upload - ' . $videoTitle);
            $snippet = new Google_Service_YouTube_VideoSnippet();
            $snippet->setTitle($videoTitle);
            $snippet->setDescription($videoDescription);
            $snippet->setTags(${$videoTags});
            $snippet->setCategoryId($videoCategory);
            $status = new Google_Service_YouTube_VideoStatus();
            $status->privacyStatus = "private";
            //TODO: UPDATE YOUR UPLOAD VIDEO STATUS , (private/public)
            $video = new Google_Service_YouTube_Video();
            $video->setSnippet($snippet);
            $video->setStatus($status);
            $chunkSizeBytes = 1 * 1024 * 1024;
            $client->setDefer(true);
            $insertRequest = $youtube->videos->insert("status,snippet", $video);
            $media = new Google_Http_MediaFileUpload($client, $insertRequest, 'video/*', null, true, $chunkSizeBytes);
            $media->setFileSize(filesize($videoPath));
            $status = false;
            $handle = fopen($videoPath, "rb");
            while (!$status && !feof($handle)) {
                $chunk = fread($handle, $chunkSizeBytes);
                $status = $media->nextChunk($chunk);
            }
            fclose($handle);
            $client->setDefer(false);
            logStatus('Video Uploaded -' . $status['snippet']['title'] . ' ' . $status['id']);
            saveYoutubePath($status['id']);
        } catch (Google_Service_Exception $e) {
            logStatus($e->getMessage());
            exit;
        } catch (Google_Exception $e) {
            logStatus($e->getMessage());
            exit;
        }
    } else {
        $state = mt_rand();
        $client->setState($state);
        $authUrl = $client->createAuthUrl();
        logStatus($authUrl);
        exit;
    }
}
Exemplo n.º 11
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;
 }
Exemplo n.º 12
0
 function google($video_temp = '', $video_name = '', $video_desc = '')
 {
     $OAUTH2_CLIENT_ID = '353001433162-42vrona3fi8msfve7akh857t6fk0di9v.apps.googleusercontent.com';
     $OAUTH2_CLIENT_SECRET = 'cEcHT7CkTK5GYUDmC7dgYa8r';
     $redirect = 'http://localhost/multitvfinal/index.php/video/google';
     $client = new Google_Client();
     $client->setClientId($OAUTH2_CLIENT_ID);
     $client->setClientSecret($OAUTH2_CLIENT_SECRET);
     $client->setScopes('https://www.googleapis.com/auth/youtube');
     $redirect = filter_var('http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'], FILTER_SANITIZE_URL);
     $client->setRedirectUri($redirect);
     $youtube = new Google_Service_YouTube($client);
     if (isset($_GET['code'])) {
         if (strval($this->session->userdata('state')) !== strval($_GET['state'])) {
             die('The session state did not match.');
         }
         $client->authenticate($_GET['code']);
         $this->session->set_userdata('token', $client->getAccessToken());
         header('Location: ' . $redirect);
     }
     $session_token = $this->session->userdata('token');
     if ($session_token) {
         $client->setAccessToken($this->session->userdata('token'));
     }
     if ($client->getAccessToken()) {
         if (isset($video_temp) && $video_temp != '') {
             // REPLACE this value with the path to the file you are uploading.
             $videoPath = $video_temp;
             // Create a snippet with title, description, tags and category ID
             // Create an asset resource and set its snippet metadata and type.
             // This example sets the video's title, description, keyword tags, and
             // video category.
             $snippet = new Google_Service_YouTube_VideoSnippet();
             $snippet->setTitle($video_name);
             $snippet->setDescription($video_desc);
             $snippet->setTags(array("globalPunjab", "Video"));
             // Numeric video category. See
             // https://developers.google.com/youtube/v3/docs/videoCategories/list
             $snippet->setCategoryId("22");
             $snippet->setChannelTitle("GlobalPunjab");
             // Set the video's status to "public". Valid statuses are "public",
             // "private" and "unlisted".
             $status = new Google_Service_YouTube_VideoStatus();
             $status->privacyStatus = "public";
             // Associate the snippet and status objects with a new video resource.
             $video = new Google_Service_YouTube_Video();
             $video->setSnippet($snippet);
             $video->setStatus($status);
             // Specify the size of each chunk of data, in bytes. Set a higher value for
             // reliable connection as fewer chunks lead to faster uploads. Set a lower
             // value for better recovery on less reliable connections.
             $chunkSizeBytes = 1 * 1024 * 1024;
             // Setting the defer flag to true tells the client to return a request which can be called
             // with ->execute(); instead of making the API call immediately.
             $client->setDefer(true);
             // Create a request for the API's videos.insert method to create and upload the video.
             $insertRequest = $youtube->videos->insert("status,snippet", $video);
             // Create a MediaFileUpload object for resumable uploads.
             $media = new Google_Http_MediaFileUpload($client, $insertRequest, 'video/*', null, true, $chunkSizeBytes);
             $media->setFileSize(filesize($videoPath));
             // Read the media file and upload it chunk by chunk.
             $status = false;
             $handle = fopen($videoPath, "rb");
             while (!$status && !feof($handle)) {
                 $chunk = fread($handle, $chunkSizeBytes);
                 $status = $media->nextChunk($chunk);
             }
             fclose($handle);
             // If you want to make other calls after the file upload, set setDefer back to false
             $client->setDefer(false);
             $htmlBody = $status['id'];
             //echo "<pre>"; print_r($status);
         }
         $htmlBody = false;
     } else {
         // If the user hasn't authorized the app, initiate the OAuth flow
         $state = mt_rand();
         $client->setState($state);
         $this->session->set_userdata('state', $state);
         //echo $this->session->userdata('state');
         $authUrl = $client->createAuthUrl();
         $htmlBody = $authUrl;
     }
     return $htmlBody;
     //spl_autoload_register('google_api_php_client_autoload'); die;
 }
 /**
  * @param $archive
  * @param $client
  * @param $request
  * @param $mime
  *
  * @return \Google_Http_MediaFileUpload
  */
 protected function getMediaUploadFile($archive, $client, $request, $mime)
 {
     $media = new \Google_Http_MediaFileUpload($client, $request, $mime, null, true, self::CHUNK_SIZE_BYTES);
     $media->setFileSize(filesize($archive));
     return $media;
 }
 public function youtube_upload($video = "linkedin.mp4", $title = "tvn rahul youtube api v3", $desc = "tvn rahul youtube api v3 for php", $tags = ["rahultvn", "youtubeapi3"], $privacy_status = "public")
 {
     $result = [];
     $htmlBody = "";
     $OAUTH2_CLIENT_ID = $this->ci->config->item('OAUTH2_CLIENT_ID');
     //'980811603180-qlbtavji7o0ekejgerqifous319d2he2.apps.googleusercontent.com';
     $OAUTH2_CLIENT_SECRET = $this->ci->config->item('OAUTH2_CLIENT_SECRET');
     //'sbzALHg38sB9aXEo0a9GG4ZA';
     $client = new Google_Client();
     $client->setClientId($OAUTH2_CLIENT_ID);
     $client->setClientSecret($OAUTH2_CLIENT_SECRET);
     $client->setScopes('https://www.googleapis.com/auth/youtube');
     $redirect = $this->ci->config->item('REDIRECT_URI');
     //filter_var('http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'],
     //FILTER_SANITIZE_URL);
     $client->setRedirectUri($redirect);
     // Define an object that will be used to make all API requests.
     $youtube = new Google_Service_YouTube($client);
     if (isset($_GET['code'])) {
         if (strval($_SESSION['state']) !== strval($_GET['state'])) {
             die('The session state did not match.');
         }
         $client->authenticate($_GET['code']);
         $_SESSION['token'] = $client->getAccessToken();
         header('Location: ' . $redirect);
     }
     if (isset($_SESSION['token'])) {
         $client->setAccessToken($_SESSION['token']);
     }
     // Check to ensure that the access token was successfully acquired.
     if ($client->getAccessToken()) {
         //echo $client->getAccessToken();
         try {
             // REPLACE this value with the path to the file you are uploading.
             $videoPath = realpath(APPPATH . '../videos/' . $video);
             //$videoPath = "videos/linkedin.mp4";
             // Create a snippet with title, description, tags and category ID
             // Create an asset resource and set its snippet metadata and type.
             // This example sets the video's title, description, keyword tags, and
             // video category.
             $snippet = new Google_Service_YouTube_VideoSnippet();
             $snippet->setTitle($title);
             $snippet->setDescription($desc);
             $snippet->setTags($tags);
             // Numeric video category. See
             // https://developers.google.com/youtube/v3/docs/videoCategories/list
             $snippet->setCategoryId("22");
             // Set the video's status to "public". Valid statuses are "public",
             // "private" and "unlisted".
             $status = new Google_Service_YouTube_VideoStatus();
             $status->privacyStatus = $privacy_status;
             // Associate the snippet and status objects with a new video resource.
             $video = new Google_Service_YouTube_Video();
             $video->setSnippet($snippet);
             $video->setStatus($status);
             // Specify the size of each chunk of data, in bytes. Set a higher value for
             // reliable connection as fewer chunks lead to faster uploads. Set a lower
             // value for better recovery on less reliable connections.
             $chunkSizeBytes = 1 * 1024 * 1024;
             // Setting the defer flag to true tells the client to return a request which can be called
             // with ->execute(); instead of making the API call immediately.
             $client->setDefer(true);
             // Create a request for the API's videos.insert method to create and upload the video.
             $insertRequest = $youtube->videos->insert("status,snippet", $video);
             // Create a MediaFileUpload object for resumable uploads.
             $media = new Google_Http_MediaFileUpload($client, $insertRequest, 'video/*', null, true, $chunkSizeBytes);
             $media->setFileSize(filesize($videoPath));
             // Read the media file and upload it chunk by chunk.
             $status = false;
             $handle = fopen($videoPath, "rb");
             while (!$status && !feof($handle)) {
                 $chunk = fread($handle, $chunkSizeBytes);
                 $status = $media->nextChunk($chunk);
             }
             fclose($handle);
             // If you want to make other calls after the file upload, set setDefer back to false
             $client->setDefer(false);
             $htmlBody .= "<h3>Video Uploaded</h3><ul>";
             $htmlBody .= sprintf('<li>%s (%s)</li>', $status['snippet']['title'], $status['id']);
             $htmlBody .= '</ul>';
             $result['id'] = $status['id'];
             $result['title'] = $status['snippet']['title'];
         } catch (Google_Service_Exception $e) {
             $htmlBody .= sprintf('<p>A service error occurred: <code>%s</code></p>', htmlspecialchars($e->getMessage()));
         } catch (Google_Exception $e) {
             $htmlBody .= sprintf('<p>An client error occurred: <code>%s</code></p>', htmlspecialchars($e->getMessage()));
         }
         $_SESSION['token'] = $client->getAccessToken();
     } else {
         // If the user hasn't authorized the app, initiate the OAuth flow
         $state = mt_rand();
         $client->setState($state);
         $_SESSION['state'] = $state;
         $authUrl = $client->createAuthUrl();
         $htmlBody .= "<h3>Authorization Required</h3>";
         $htmlBody .= "<p>You need to <a href=" . $authUrl . ">authorize access</a> before proceeding.<p>";
         $result['authUrl'] = $authUrl;
     }
     $result['message'] = $htmlBody;
     return $result;
 }
Exemplo n.º 15
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;
 }
Exemplo n.º 16
0
 public function connect_google($in_upload_state = "")
 {
     set_include_path(get_include_path() . PATH_SEPARATOR . BASEPATH . '../assets/google_api/src');
     require_once 'Google/Client.php';
     require_once 'Google/Service/YouTube.php';
     $this->load->library('session');
     $client = new Google_Client();
     $client->setApplicationName("Zeepro youtube upload");
     $client->setClientId("652807238221-vrc4no9o0t9mdb48ltc69v215henenm4.apps.googleusercontent.com");
     $client->setClientSecret("PPww8vp8cOVcqeHioL7HbCFx");
     $client->setScopes('https://www.googleapis.com/auth/youtube');
     $redirect = filter_var('https://sso.zeepro.com/redirect.ashx', FILTER_SANITIZE_URL);
     $client->setRedirectUri($redirect);
     $client->setAccessType('offline');
     $youtube = new Google_Service_YouTube($client);
     if (isset($_GET['code'])) {
         if (strval($this->session->userdata('state')) !== strval($_GET['state'])) {
             var_dump($this->session->all_userdata());
             die('The session state did not match.');
         }
         $client->authenticate($_GET['code']);
         $this->session->set_userdata('token', $client->getAccessToken());
         $this->session->set_userdata('code', $_GET['code']);
     }
     if ($this->session->userdata('token') !== FALSE) {
         $client->setAccessToken($this->session->userdata('token'));
         if ($client->isAccessTokenExpired()) {
             $currentTokenData = json_decode($this->session->userdata('token'));
             if (isset($currentTokenData->refresh_token)) {
                 $client->refreshToken($tokenData->refresh_token);
             }
         }
     }
     if ($client->getAccessToken() && $in_upload_state != "") {
         $this->load->helper('zimapi');
         try {
             $videoPath = ZIMAPI_FILEPATH_TIMELAPSE;
             // Create a snippet with title, description, tags and category ID
             // Create an asset resource and set its snippet metadata and type.
             // This example sets the video's title, description, keyword tags, and
             // video category.
             $snippet = new Google_Service_YouTube_VideoSnippet();
             $snippet->setTitle($this->session->userdata('yt_title'));
             $snippet->setDescription($this->session->userdata("yt_desc"));
             $snippet->setTags($this->session->userdata("yt_tags"));
             // Numeric video category. See https://developers.google.com/youtube/v3/docs/videoCategories/list
             $snippet->setCategoryId("22");
             // Set the video's status to "public". Valid statuses are "public", "private" and "unlisted".
             $status = new Google_Service_YouTube_VideoStatus();
             $status->privacyStatus = $this->session->userdata('yt_privacy');
             // Associate the snippet and status objects with a new video resource.
             $video = new Google_Service_YouTube_Video();
             $video->setSnippet($snippet);
             $video->setStatus($status);
             // Specify the size of each chunk of data, in bytes. Set a higher value for
             // reliable connection as fewer chunks lead to faster uploads. Set a lower
             // value for better recovery on less reliable connections.
             $chunkSizeBytes = 1 * 1024 * 1024;
             // Setting the defer flag to true tells the client to return a request which can be called
             // with ->execute(); instead of making the API call immediately.
             $client->setDefer(true);
             // Create a request for the API's videos.insert method to create and upload the video.
             $insertRequest = $youtube->videos->insert("status,snippet", $video);
             // Create a MediaFileUpload object for resumable uploads.
             $media = new Google_Http_MediaFileUpload($client, $insertRequest, 'video/mp4', null, true, $chunkSizeBytes);
             $media->setFileSize(filesize($videoPath));
             // Read the media file and upload it chunk by chunk.
             $status = false;
             $handle = fopen($videoPath, "rb");
             while (!$status && !feof($handle)) {
                 $chunk = fread($handle, $chunkSizeBytes);
                 $status = $media->nextChunk($chunk);
             }
             fclose($handle);
             $client->setDefer(false);
             $this->session->unset_userdata(array('yt_title', 'yt_desc', 'yt_tags', 'yt_privacy'));
             echo "<h3>Video Uploaded</h3><ul>";
             echo sprintf('<li>%s (%s)</li>', $status['snippet']['title'], $status['id']);
             echo '</ul>';
             //stats info
             $this->load->helper('printerlog');
             PrinterLog_statsShareVideo(PRINTERLOG_STATS_LABEL_YOUTUBE);
         } catch (Google_ServiceException $e) {
             $this->_exitWithError500(sprintf('<p>A service error occurred: <code>%s</code></p>', htmlspecialchars($e->getMessage())));
         } catch (Google_Exception $e) {
             $this->_exitWithError500(sprintf('<p>An client error occurred: <code>%s</code></p>', htmlspecialchars($e->getMessage())));
         }
         $this->session->set_userdata('token', $client->getAccessToken());
     } else {
         $this->load->helper(array('zimapi', 'corestatus'));
         $prefix = CoreStatus_checkTromboning() ? 'https://' : 'http://';
         $data = array('printersn' => ZimAPI_getSerial(), 'URL' => $prefix . $_SERVER['HTTP_HOST'] . '/share/video_upload');
         $options = array('http' => array('header' => "Content-type: application/x-www-form-urlencoded\r\n", 'method' => 'POST', 'content' => http_build_query($data)));
         $context = stream_context_create($options);
         @file_get_contents('https://sso.zeepro.com/url.ashx', false, $context);
         $result = substr($http_response_header[0], 9, 3);
         if ($result == 200) {
             //echo 'ca marche';
         }
         $state = ZimAPI_getSerial();
         $client->setState($state);
         $this->session->set_userdata('state', $state);
         $authUrl = $client->createAuthUrl();
         $this->output->set_header("Location: " . $authUrl);
     }
     return;
 }
Exemplo n.º 17
0
 /**
  * TODO: This function needs simplifying.
  * @param $name
  * @param $arguments
  * @param $expectedClass - optional, the expected class name
  * @return Google_Http_Request|expectedClass
  * @throws Google_Exception
  */
 public function call($name, $arguments, $expectedClass = null)
 {
     if (!isset($this->methods[$name])) {
         $this->client->getLogger()->error('Service method unknown', array('service' => $this->serviceName, 'resource' => $this->resourceName, 'method' => $name));
         throw new Google_Exception("Unknown function: " . "{$this->serviceName}->{$this->resourceName}->{$name}()");
     }
     $method = $this->methods[$name];
     $parameters = $arguments[0];
     // postBody is a special case since it's not defined in the discovery
     // document as parameter, but we abuse the param entry for storing it.
     $postBody = null;
     if (isset($parameters['postBody'])) {
         if ($parameters['postBody'] instanceof Google_Model) {
             // In the cases the post body is an existing object, we want
             // to use the smart method to create a simple object for
             // for JSONification.
             $parameters['postBody'] = $parameters['postBody']->toSimpleObject();
         } else {
             if (is_object($parameters['postBody'])) {
                 // If the post body is another kind of object, we will try and
                 // wrangle it into a sensible format.
                 $parameters['postBody'] = $this->convertToArrayAndStripNulls($parameters['postBody']);
             }
         }
         $postBody = (array) $parameters['postBody'];
         unset($parameters['postBody']);
     }
     // TODO: optParams here probably should have been
     // handled already - this may well be redundant code.
     if (isset($parameters['optParams'])) {
         $optParams = $parameters['optParams'];
         unset($parameters['optParams']);
         $parameters = array_merge($parameters, $optParams);
     }
     if (!isset($method['parameters'])) {
         $method['parameters'] = array();
     }
     $method['parameters'] = array_merge($this->stackParameters, $method['parameters']);
     foreach ($parameters as $key => $val) {
         if ($key != 'postBody' && !isset($method['parameters'][$key])) {
             $this->client->getLogger()->error('Service parameter unknown', array('service' => $this->serviceName, 'resource' => $this->resourceName, 'method' => $name, 'parameter' => $key));
             throw new Google_Exception("({$name}) unknown parameter: '{$key}'");
         }
     }
     foreach ($method['parameters'] as $paramName => $paramSpec) {
         if (isset($paramSpec['required']) && $paramSpec['required'] && !isset($parameters[$paramName])) {
             $this->client->getLogger()->error('Service parameter missing', array('service' => $this->serviceName, 'resource' => $this->resourceName, 'method' => $name, 'parameter' => $paramName));
             throw new Google_Exception("({$name}) missing required param: '{$paramName}'");
         }
         if (isset($parameters[$paramName])) {
             $value = $parameters[$paramName];
             $parameters[$paramName] = $paramSpec;
             $parameters[$paramName]['value'] = $value;
             unset($parameters[$paramName]['required']);
         } else {
             // Ensure we don't pass nulls.
             unset($parameters[$paramName]);
         }
     }
     $this->client->getLogger()->info('Service Call', array('service' => $this->serviceName, 'resource' => $this->resourceName, 'method' => $name, 'arguments' => $parameters));
     // build the service uri
     $url = $this->createRequestUri($method['path'], $parameters);
     // NOTE: because we're creating the request by hand,
     // and because the service has a rootUrl property
     // the "base_uri" of the Http Client is not accounted for
     $request = new Request($method['httpMethod'], $url, ['content-type' => 'application/json'], $postBody ? json_encode($postBody) : '');
     // support uploads
     if (isset($parameters['data'])) {
         $mimeType = isset($parameters['mimeType']) ? $parameters['mimeType']['value'] : 'application/octet-stream';
         $data = $parameters['data']['value'];
         $upload = new Google_Http_MediaFileUpload($this->client, $request, $mimeType, $data);
         // pull down the modified request
         $request = $upload->getRequest();
     }
     // if this is a media type, we will return the raw response
     // rather than using an expected class
     if (isset($parameters['alt']) && $parameters['alt']['value'] == 'media') {
         $expectedClass = null;
     }
     // if the client is marked for deferring, rather than
     // execute the request, return the response
     if ($this->client->shouldDefer()) {
         // @TODO find a better way to do this
         $request = $request->withHeader('X-Php-Expected-Class', $expectedClass);
         return $request;
     }
     return $this->client->execute($request, $expectedClass);
 }
 public function google_access($flag)
 {
     include_once APPPATH . "third_party/Google/autoload.php";
     //include_once APPPATH . "libraries/Google/Client.php";
     //include_once APPPATH . "libraries/google-api-php-client-master/src/Google/Service/Oauth2.php";
     //include_once APPPATH . "libraries/Google/Service/Youtube.php";
     $scope = array('https://www.googleapis.com/auth/youtube.upload', 'https://www.googleapis.com/auth/youtube', 'https://www.googleapis.com/auth/youtubepartner');
     $client = new Google_Client();
     $client->setClientId($this->client_id);
     $client->setClientSecret($this->client_secret);
     //$client->setScopes('https://www.googleapis.com/auth/youtube');
     $client->setScopes($scope);
     $client->setRedirectUri($this->redirect_uri);
     $client->setApplicationName($this->application_name);
     $client->setAccessType('offline');
     $youtube = new Google_Service_YouTube($client);
     if (isset($_GET['code'])) {
         $client->authenticate($_GET['code']);
         $_SESSION['token'] = $client->getAccessToken();
     }
     if ($flag == '') {
         if (isset($_SESSION['token'])) {
             $client->setAccessToken($_SESSION['token']);
             $client->getAccessToken();
             $_SESSION['token'] = $client->getAccessToken();
             //unset($_SESSION['token']);
             var_dump($_SESSION);
             return 1;
         } else {
             $authUrl = $client->createAuthUrl();
             $string = '<script src="' . base_url() . '"assets/jquery-1.10.2.js"></script><a id="load_page" href="' . $authUrl . '">Connect Me!!</a><script>window.location = $("#load_page"").attr(""href");</script>';
             return $string;
         }
     }
     if ($flag) {
         if (isset($_SESSION['token'])) {
             $client->setAccessToken($_SESSION['token']);
             $client->getAccessToken();
             $_SESSION['token'] = $client->getAccessToken();
             try {
                 /*if($client->isAccessTokenExpired()) 
                 		{
                 			$newToken = json_decode($client->getAccessToken());
                 			$client->refreshToken($newToken->access_token);
                 		}*/
                 $video_det = explode(',', $flag);
                 // $video_det[0],	$video_det[1];
                 $videoPath = $video_det[0];
                 $videoTitle = $video_det[1];
                 $videoDescription = "A video tutorial on how to upload to YouTube";
                 $videoCategory = "22";
                 $videoTags = array("youtube", "tutorial");
                 $youtube = new Google_Service_YouTube($client);
                 // Create a snipet with title, description, tags and category id
                 $snippet = new Google_Service_YouTube_VideoSnippet();
                 $snippet->setTitle($videoTitle);
                 $snippet->setDescription($videoDescription);
                 $snippet->setCategoryId($videoCategory);
                 $snippet->setTags($videoTags);
                 // Create a video status with privacy status. Options are "public", "private" and "unlisted".
                 $status = new Google_Service_YouTube_VideoStatus();
                 $status->setPrivacyStatus('private');
                 // Create a YouTube video with snippet and status
                 $video = new Google_Service_YouTube_Video();
                 $video->setSnippet($snippet);
                 $video->setStatus($status);
                 // Size of each chunk of data in bytes. Setting it higher leads faster upload (less chunks,
                 // for reliable connections). Setting it lower leads better recovery (fine-grained chunks)
                 $chunkSizeBytes = 1 * 1024 * 1024;
                 // Setting the defer flag to true tells the client to return a request which can be called
                 // with ->execute(); instead of making the API call immediately.
                 $client->setDefer(true);
                 // Create a request for the API's videos.insert method to create and upload the video.
                 $insertRequest = $youtube->videos->insert("status,snippet", $video);
                 // Create a MediaFileUpload object for resumable uploads.
                 $media = new Google_Http_MediaFileUpload($client, $insertRequest, 'video/*', null, true, $chunkSizeBytes);
                 $media->setFileSize(filesize($videoPath));
                 //var_dump(filesize($videoPath));
                 // Read the media file and upload it chunk by chunk.
                 $status = false;
                 $handle = fopen($videoPath, "rb");
                 while (!$status && !feof($handle)) {
                     $chunk = fread($handle, $chunkSizeBytes);
                     $status = $media->nextChunk($chunk);
                 }
                 fclose($handle);
                 // Video has successfully been upload, now lets perform some cleanup functions for this video
                 if ($status->status['uploadStatus'] == 'uploaded') {
                     // Actions to perform for a successful upload
                     redirect('home', 'refresh');
                 }
                 // If you want to make other calls after the file upload, set setDefer back to false
                 $client->setDefer(false);
             } catch (Google_Service_Exception $e) {
                 print "Caught Google service Exception " . $e->getCode() . " message is " . $e->getMessage();
                 print "Stack trace is " . $e->getTraceAsString();
             } catch (Exception $e) {
                 print "Caught Google service Exception " . $e->getCode() . " message is " . $e->getMessage();
                 print "Stack trace is " . $e->getTraceAsString();
             }
         } else {
             $authUrl = $client->createAuthUrl();
             $string = '<script src="' . base_url() . 'assets/jquery-1.10.2.js"></script><a id="load_page" href="' . $authUrl . '">Connect Me!!</a><script>window.location = $("#load_page"").attr(""href");</script>';
             return $string;
         }
         if ($client->getAccessToken()) {
             try {
                 // Call the channels.list method to retrieve information about the
                 // currently authenticated user's channel.
                 $channelsResponse = $youtube->channels->listChannels('contentDetails', array('mine' => 'true'));
                 $htmlBody = '';
                 foreach ($channelsResponse['items'] as $channel) {
                     // Extract the unique playlist ID that identifies the list of videos
                     // uploaded to the channel, and then call the playlistItems.list method
                     // to retrieve that list.
                     $uploadsListId = $channel['contentDetails']['relatedPlaylists']['uploads'];
                     $playlistItemsResponse = $youtube->playlistItems->listPlaylistItems('snippet', array('playlistId' => $uploadsListId, 'maxResults' => 50));
                     $htmlBody .= "<h3>Videos in list {$uploadsListId}</h3><ul>";
                     foreach ($playlistItemsResponse['items'] as $playlistItem) {
                         $htmlBody .= sprintf('<li>%s (%s)</li>', $playlistItem['snippet']['title'], $playlistItem['snippet']['resourceId']['videoId']);
                     }
                     $htmlBody .= '</ul>';
                 }
             } catch (Google_ServiceException $e) {
                 $htmlBody .= sprintf('<p>A service error occurred: <code>%s</code></p>', htmlspecialchars($e->getMessage()));
             } catch (Google_Exception $e) {
                 $htmlBody .= sprintf('<p>An client error occurred: <code>%s</code></p>', htmlspecialchars($e->getMessage()));
             }
             $_SESSION['token'] = $client->getAccessToken();
         } else {
             $state = mt_rand();
             $client->setState($state);
             $_SESSION['state'] = $state;
             $authUrl = $client->createAuthUrl();
             $string = '<script src="' . base_url() . '"assets/jquery-1.10.2.js"></script><a id="load_page" href="' . $authUrl . '">Connect Me!!</a><script>window.location = $("#load_page"").attr(""href");</script>';
             return $string;
         }
     }
 }
Exemplo n.º 19
0
 public function uploadVideosChannel()
 {
     // Call set_include_path() as needed to point to your client library.
     set_time_limit(0);
     require_once 'Google/autoload.php';
     require_once 'Google/Client.php';
     require_once 'Google/Service/YouTube.php';
     session_start();
     $htmlBody = "";
     /*
      * You can acquire an OAuth 2.0 client ID and client secret from the
      * Google Developers Console <https://console.developers.google.com/>
      * For more information about using OAuth 2.0 to access Google APIs, please see:
      * <https://developers.google.com/youtube/v3/guides/authentication>
      * Please ensure that you have enabled the YouTube Data API for your project.
      */
     $settings = Engine_Api::_()->getApi('settings', 'core');
     $user_youtube_allow = $settings->getSetting('user_youtube_allow');
     if (!$user_youtube_allow) {
         return false;
     }
     $token = $settings->getSetting('user_youtube_token', "");
     $OAUTH2_CLIENT_ID = $settings->getSetting('user_youtube_clientid', "");
     $OAUTH2_CLIENT_SECRET = $settings->getSetting('user_youtube_secret', "");
     if (empty($token) || empty($token) || empty($token)) {
         return fasle;
     }
     //getting videos
     $videoTable = Engine_Api::_()->getItemTable('video');
     $select = $videoTable->select()->where('file_id <> ?', '0')->limit(2);
     $videos = $videoTable->fetchAll($select);
     foreach ($videos as $videoLoop) {
         $client = new Google_Client();
         $client->setClientId($OAUTH2_CLIENT_ID);
         $client->setClientSecret($OAUTH2_CLIENT_SECRET);
         $client->setAccessType('offline');
         $client->setScopes('https://www.googleapis.com/auth/youtube');
         $redirect = filter_var('http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'], FILTER_SANITIZE_URL);
         $redirect = str_replace("index.php", "admin/user/youtube/token", $redirect);
         $client->setRedirectUri($redirect);
         $client->setAccessToken($token);
         /**
          * Check to see if our access token has expired. If so, get a new one and save it to file for future use.
          */
         if ($client->isAccessTokenExpired()) {
             $newToken = json_decode($client->getAccessToken());
             $client->refreshToken($newToken->refresh_token);
             $settings->setSetting('user_youtube_token', $client->getAccessToken());
         }
         // Check to ensure that the access token was successfully acquired.
         if ($client->getAccessToken()) {
             try {
                 // Define an object that will be used to make all API requests.
                 $youtube = new Google_Service_YouTube($client);
                 //get info of files
                 $file = Engine_Api::_()->getItem('storage_file', $videoLoop->file_id);
                 if (!file) {
                     continue;
                 }
                 // REPLACE this value with the path to the file you are uploading.
                 $videoPath = $file->storage_path;
                 // Create a snippet with title, description, tags and category ID
                 // Create an asset resource and set its snippet metadata and type.
                 // This example sets the video's title, description, keyword tags, and
                 // video category.
                 $snippet = new Google_Service_YouTube_VideoSnippet();
                 $snippet->setTitle($videoLoop->getTitle());
                 $snippet->setDescription($videoLoop->getDescription());
                 // Numeric video category. See
                 // https://developers.google.com/youtube/v3/docs/videoCategories/list
                 $snippet->setCategoryId("22");
                 // Set the video's status to "public". Valid statuses are "public",
                 // "private" and "unlisted".
                 $status = new Google_Service_YouTube_VideoStatus();
                 $status->privacyStatus = "public";
                 // Associate the snippet and status objects with a new video resource.
                 $video = new Google_Service_YouTube_Video();
                 $video->setSnippet($snippet);
                 $video->setStatus($status);
                 // Specify the size of each chunk of data, in bytes. Set a higher value for
                 // reliable connection as fewer chunks lead to faster uploads. Set a lower
                 // value for better recovery on less reliable connections.
                 $chunkSizeBytes = 1 * 1024 * 1024;
                 // Setting the defer flag to true tells the client to return a request which can be called
                 // with ->execute(); instead of making the API call immediately.
                 $client->setDefer(true);
                 // Create a request for the API's videos.insert method to create and upload the video.
                 $insertRequest = $youtube->videos->insert("status,snippet", $video);
                 // Create a MediaFileUpload object for resumable uploads.
                 $media = new Google_Http_MediaFileUpload($client, $insertRequest, 'video/*', null, true, $chunkSizeBytes);
                 $media->setFileSize(filesize($videoPath));
                 // Read the media file and upload it chunk by chunk.
                 $status = false;
                 $handle = fopen($videoPath, "rb");
                 while (!$status && !feof($handle)) {
                     $chunk = fread($handle, $chunkSizeBytes);
                     $status = $media->nextChunk($chunk);
                 }
                 fclose($handle);
                 // If you want to make other calls after the file upload, set setDefer back to false
                 $client->setDefer(false);
                 //update video data
                 $videoLoop->code = $status['id'];
                 $videoLoop->file_id = 0;
                 $videoLoop->type = 1;
                 $videoLoop->status = 1;
                 $videoLoop->save();
                 //delete old video
                 $file->delete();
                 //echo $status['id'];
                 //$htmlBody .= "<h3>Video Uploaded</h3><ul>";
                 //$htmlBody .= sprintf('<li>%s (%s)</li>',
                 //    $status['snippet']['title'],
                 //    $status['id']);
                 $htmlBody .= '</ul>';
             } catch (Google_Service_Exception $e) {
                 //$htmlBody .= sprintf('<p>A service error occurred: <code>%s</code></p>',
                 //    htmlspecialchars($e->getMessage()));
                 continue;
             } catch (Google_Exception $e) {
                 //$htmlBody .= sprintf('<p>An client error occurred: <code>%s</code></p>',
                 //    htmlspecialchars($e->getMessage()));
                 continue;
             }
         }
     }
     //echo $htmlBody;
 }
Exemplo n.º 20
0
function insertFileResumable(&$service, &$client, $title, $description, $parentId, $mimeType, $filepath, &$configObj)
{
    $file = new Google_Service_Drive_DriveFile();
    $file->setTitle($title);
    $file->setDescription($description);
    $file->setMimeType($mimeType);
    $chunkSizeBytes = 1 * 1024 * 1024;
    if ($parentId != null) {
        $parent = new Google_Service_Drive_ParentReference();
        $parent->setId($parentId);
        $file->setParents(array($parent));
    }
    // Call the API with the media upload, defer so it doesn't immediately return.
    $client->setDefer(true);
    $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));
    // Upload the various chunks. $status will be false until the process is
    // complete.
    $status = false;
    $handle = fopen($filepath, "rb");
    while (!$status && !feof($handle)) {
        for ($n = 0; $n < 5; ++$n) {
            try {
                $chunk = fread($handle, $chunkSizeBytes);
                $status = $media->nextChunk($chunk);
                break;
            } 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);
                    usleep((1 << $n) * 1000000 + rand(0, 1000000));
                }
            } catch (Exception $e) {
                $logline = date('Y-m-d H:i:s') . " Error: " . $e->getMessage() . "\n";
                fwrite($configObj->logFile, $logline);
                throw $e;
            }
        }
    }
    fclose($handle);
    // Reset to the client to execute requests immediately in the future.
    $client->setDefer(false);
    return;
}
Exemplo n.º 21
0
 /**
  * Upload the video to YouTube
  * @param  string 	$path    	The path to the file you wish to upload.
  * @param  array 	$snippet 	An array of data.
  * @param  string 	$status  	The status of the uploaded video, set to 'public' by default.
  * @return mixed
  */
 public function upload($path, array $data, $privacyStatus = 'public')
 {
     $this->handleAccessToken();
     /* ------------------------------------
     		#. Setup the Snippet
     		------------------------------------ */
     $snippet = new \Google_Service_YouTube_VideoSnippet();
     if (array_key_exists('title', $data)) {
         $snippet->setTitle($data['title']);
     }
     if (array_key_exists('description', $data)) {
         $snippet->setDescription($data['description']);
     }
     if (array_key_exists('tags', $data)) {
         $snippet->setTags($data['tags']);
     }
     if (array_key_exists('category_id', $data)) {
         $snippet->setCategoryId($data['category_id']);
     }
     /* ------------------------------------
     		#. Set the Privacy Status
     		------------------------------------ */
     $status = new \Google_Service_YouTube_VideoStatus();
     $status->privacyStatus = $privacyStatus;
     /* ------------------------------------
     		#. Set the Snippet & Status
     		------------------------------------ */
     $video = new \Google_Service_YouTube_Video();
     $video->setSnippet($snippet);
     $video->setStatus($status);
     /* ------------------------------------
     		#. Set the Chunk Size
     		------------------------------------ */
     $chunkSize = 1 * 1024 * 1024;
     /* ------------------------------------
     		#. Set the defer to true
     		------------------------------------ */
     $this->client->setDefer(true);
     /* ------------------------------------
     		#. Build the request
     		------------------------------------ */
     $insert = $this->youtube->videos->insert('status,snippet', $video);
     /* ------------------------------------
     		#. Upload
     		------------------------------------ */
     $media = new \Google_Http_MediaFileUpload($this->client, $insert, 'video/*', null, true, $chunkSize);
     /* ------------------------------------
     		#. Set the Filesize
     		------------------------------------ */
     $media->setFileSize(filesize($path));
     /* ------------------------------------
     		#. Read the file and upload in chunks
     		------------------------------------ */
     $status = false;
     $handle = fopen($path, "rb");
     while (!$status && !feof($handle)) {
         $chunk = fread($handle, $chunkSize);
         $status = $media->nextChunk($chunk);
     }
     fclose($handle);
     /* ------------------------------------
     		#. Set the defer to false again
     		------------------------------------ */
     $this->client->setDefer(true);
     /* ------------------------------------
     		#. Return the Uploaded Video ID
     		------------------------------------ */
     return $status['id'];
 }
Exemplo n.º 22
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;
 }
Exemplo n.º 23
0
/**
 * Updates a caption track's draft status to publish it.
 * Updates the track with a new binary file as well if it is present.  (captions.update)
 *
 * @param Google_Service_YouTube $youtube YouTube service object.
 * @param Google_Client $client Google client.
 * @param string $captionId The id parameter specifies the caption ID for the resource
 * that is being updated. In a caption resource, the id property specifies the
 * caption track's ID.
 * @param $htmlBody - html body.
 * @param $captionFile caption track binary file.
 */
function updateCaption(Google_Service_YouTube $youtube, Google_Client $client, $captionId, &$htmlBody, $captionFile)
{
    // Modify caption's isDraft property to unpublish a caption track.
    $updateCaptionSnippet = new Google_Service_YouTube_CaptionSnippet();
    $updateCaptionSnippet->setIsDraft(true);
    # Create a caption with snippet.
    $updateCaption = new Google_Service_YouTube_Caption();
    $updateCaption->setSnippet($updateCaptionSnippet);
    $updateCaption->setId($captionId);
    if ($captionFile == '') {
        // Call the YouTube Data API's captions.update method to update an existing caption track.
        $captionUpdateResponse = $youtube->captions->update("snippet", $updateCaption);
        $htmlBody .= "<h2>Updated caption track</h2><ul>";
        $htmlBody .= sprintf('<li>%s(%s) draft status: %s</li>', $captionUpdateResponse['snippet']['name'], $captionUpdateResponse['id'], $captionUpdateResponse['snippet']['isDraft']);
        $htmlBody .= '</ul>';
    } else {
        // Specify the size of each chunk of data, in bytes. Set a higher value for
        // reliable connection as fewer chunks lead to faster uploads. Set a lower
        // value for better recovery on less reliable connections.
        $chunkSizeBytes = 1 * 1024 * 1024;
        // Setting the defer flag to true tells the client to return a request which can be called
        // with ->execute(); instead of making the API call immediately.
        $client->setDefer(true);
        // Create a request for the YouTube Data API's captions.update method to update
        // an existing caption track.
        $captionUpdateRequest = $youtube->captions->update("snippet", $updateCaption);
        // Create a MediaFileUpload object for resumable uploads.
        $media = new Google_Http_MediaFileUpload($client, $captionUpdateRequest, '*/*', null, true, $chunkSizeBytes);
        $media->setFileSize(filesize($captionFile));
        // Read the caption file and upload it chunk by chunk.
        $status = false;
        $handle = fopen($captionFile, "rb");
        while (!$status && !feof($handle)) {
            $chunk = fread($handle, $chunkSizeBytes);
            $status = $media->nextChunk($chunk);
        }
        fclose($handle);
        // If you want to make other calls after the file upload, set setDefer back to false
        $client->setDefer(false);
        $htmlBody .= "<h2>Updated caption track</h2><ul>";
        $htmlBody .= sprintf('<li>%s(%s) draft status: %s and updated the track with
          the new uploaded file.</li>', $status['snippet']['name'], $status['id'], $status['snippet']['isDraft']);
        $htmlBody .= '</ul>';
    }
}
Exemplo n.º 24
0
 private function do_upload_engine($basename, $from, $try_again = true)
 {
     global $updraftplus;
     $opts = $this->options;
     $service = $this->service;
     list($bucket_name, $path) = $this->split_bucket_path($opts['bucket_path']);
     if (empty($bucket_name)) {
         _e("Failure: No bucket details were given.", 'updraftplus');
         return;
     }
     $bucket = $this->create_bucket_if_not_existing($bucket_name);
     if (is_wp_error($bucket)) {
         throw new Exception("Google Cloud Storage: Error accessing or creating bucket: " . $bucket->get_error_message());
     }
     $storage_object = new Google_Service_Storage_StorageObject();
     $storage_object->setName($path . $basename);
     $storage_object->setBucket($bucket_name);
     // In Google Cloud Storage, the storage class is a property of buckets, not objects - i.e. objects simply inherit from the bucket
     // 		$storage_class = (!empty($opts['storage_class']) && isset($this->storage_classes[$opts['storage_class']])) ? $opts['storage_class'] : 'STANDARD';
     // 		$storage_object->setStorageClass($storage_class);
     $this->client->setDefer(true);
     $request = $this->service->objects->insert($bucket_name, $storage_object, array('mimeType' => $updraftplus->get_mime_type_from_filename($basename), 'uploadType' => 'media'));
     $hash = md5($basename);
     $transkey = 'gcresume_' . $hash;
     // This is unset upon completion, so if it is set then we are resuming
     $possible_location = $updraftplus->jobdata_get($transkey);
     $size = 0;
     $local_size = filesize($from);
     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() . ")");
         }
     }
     // 		(('.zip' == substr($basename, -4, 4)) ? 'application/zip' : 'application/octet-stream'),
     $media = new Google_Http_MediaFileUpload($this->client, $request, $updraftplus->get_mime_type_from_filename($basename), null, true, $this->chunk_size);
     $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($from, 'rb'))) {
         $updraftplus->log("Google Cloud Storage: 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 Cloud Storage: 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, $this->chunk_size);
             # 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(), $from);
         }
     } catch (Google_Service_Exception $e) {
         $updraftplus->log("ERROR: Google Cloud Storage upload error (" . get_class($e) . "): " . $e->getMessage() . ' (line: ' . $e->getLine() . ', file: ' . $e->getFile() . ')');
         $this->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->do_upload_engine($basename, $from, 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);
     $this->client->setDefer(false);
     $updraftplus->jobdata_delete($transkey);
     return true;
 }
Exemplo n.º 25
0
} else {
    $authUrl = $client->createAuthUrl();
}
/************************************************
  If we're signed in then lets try to upload our
  file.
 ************************************************/
if ($client->getAccessToken()) {
    $file = new Google_Service_Drive_DriveFile();
    $file->title = "Big File";
    $chunkSizeBytes = 1 * 1024 * 1024;
    // Call the API with the media upload, defer so it doesn't immediately return.
    $client->setDefer(true);
    $request = $service->files->insert($file);
    // Create a media file upload to represent our upload process.
    $media = new Google_Http_MediaFileUpload($client, $request, 'text/plain', null, true, $chunkSizeBytes);
    $media->setFileSize(filesize(TESTFILE));
    // Upload the various chunks. $status will be false until the process is
    // complete.
    $status = false;
    $handle = fopen(TESTFILE, "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;
    }
Exemplo n.º 26
0
 public function testNextChunkWithMoreRemaining()
 {
     $this->checkToken();
     $client = $this->getClient();
     $client->addScope("https://www.googleapis.com/auth/drive");
     $service = new Google_Service_Drive($client);
     $chunkSizeBytes = 262144;
     // smallest chunk size allowed by APIs
     $data = str_repeat('.', $chunkSizeBytes + 1);
     $file = new Google_Service_Drive_DriveFile();
     $file->title = $title = 'TESTFILE-testNextChunkWithMoreRemaining';
     // Call the API with the media upload, defer so it doesn't immediately return.
     $client->setDefer(true);
     $request = $service->files->insert($file);
     // Create a media file upload to represent our upload process.
     $media = new Google_Http_MediaFileUpload($client, $request, 'text/plain', $data, true, $chunkSizeBytes);
     $media->setFileSize(strlen($data));
     // upload the file
     $file = $media->nextChunk();
     // false means we aren't done uploading, which is exactly what we expect!
     $this->assertFalse($file);
 }
Exemplo n.º 27
0
 /**
  * Upload file in chunks.
  *
  * @param string                       $file
  * @param \Google_Http_MediaFileUpload $media
  * @param int                          $chunkSizeBytes
  *
  * @return bool|string
  */
 protected function uploadChunks($file, \Google_Http_MediaFileUpload $media, $chunkSizeBytes)
 {
     // Upload the various chunks. $status will be false until the process is complete.
     $status = false;
     $handle = fopen($file, 'rb');
     while (!$status && !feof($handle)) {
         $chunk = $this->readVideoChunk($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);
     // Remove the local asset file
     IOHelper::deleteFile($file);
     // Return YouTube ID or false
     return $result;
 }
Exemplo n.º 28
0
 public function writeBack($tmpFile)
 {
     if (isset(self::$tempFiles[$tmpFile])) {
         $path = self::$tempFiles[$tmpFile];
         $parentFolder = $this->getDriveFile(dirname($path));
         if ($parentFolder) {
             $mimetype = \OC::$server->getMimeTypeDetector()->detect($tmpFile);
             $params = array('mimeType' => $mimetype, 'uploadType' => 'media');
             $result = false;
             $chunkSizeBytes = 10 * 1024 * 1024;
             $useChunking = false;
             $size = filesize($tmpFile);
             if ($size > $chunkSizeBytes) {
                 $useChunking = true;
             } else {
                 $params['data'] = file_get_contents($tmpFile);
             }
             if ($this->file_exists($path)) {
                 $file = $this->getDriveFile($path);
                 $this->client->setDefer($useChunking);
                 $request = $this->service->files->update($file->getId(), $file, $params);
             } else {
                 $file = new \Google_Service_Drive_DriveFile();
                 $file->setTitle(basename($path));
                 $file->setMimeType($mimetype);
                 $parent = new \Google_Service_Drive_ParentReference();
                 $parent->setId($parentFolder->getId());
                 $file->setParents(array($parent));
                 $this->client->setDefer($useChunking);
                 $request = $this->service->files->insert($file, $params);
             }
             if ($useChunking) {
                 // Create a media file upload to represent our upload process.
                 $media = new \Google_Http_MediaFileUpload($this->client, $request, 'text/plain', null, true, $chunkSizeBytes);
                 $media->setFileSize($size);
                 // Upload the various chunks. $status will be false until the process is
                 // complete.
                 $status = false;
                 $handle = fopen($tmpFile, '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);
             } else {
                 $result = $request;
             }
             // Reset to the client to execute requests immediately in the future.
             $this->client->setDefer(false);
             if ($result) {
                 $this->setDriveFile($path, $result);
             }
         }
         unlink($tmpFile);
     }
 }
Exemplo n.º 29
0
if ($client->getAccessToken()) {
    try {
        // REPLACE with the path to your file that you want to upload for thumbnail
        $imagePath = "/path/to/file.jpg";
        // Specify the size of each chunk of data, in bytes. Set a higher value for
        // reliable connection as fewer chunks lead to faster uploads. Set a lower
        // value for better recovery on less reliable connections.
        $chunkSizeBytes = 1 * 1024 * 1024;
        // Setting the defer flag to true tells the client to return a request which can be called
        // with ->execute(); instead of making the API call immediately.
        $client->setDefer(true);
        $chan = new Google_Service_YouTube_ChannelBannerResource();
        // Create a request for the API's channelBanners.insert method to upload the banner.
        $insertRequest = $youtube->channelBanners->insert($chan);
        // Create a MediaFileUpload object for resumable uploads.
        $media = new Google_Http_MediaFileUpload($client, $insertRequest, 'image/jpeg', null, true, $chunkSizeBytes);
        $media->setFileSize(filesize($imagePath));
        // Read the media file and upload it chunk by chunk.
        $status = false;
        $handle = fopen($videoPath, "rb");
        while (!$status && !feof($handle)) {
            $chunk = fread($handle, $chunkSizeBytes);
            $status = $media->nextChunk($chunk);
        }
        fclose($handle);
        // If you want to make other calls after the file upload, set setDefer back to false
        $client->setDefer(false);
        $thumbnailUrl = $status['url'];
        // Call the API's channels.list method with mine parameter to fetch authorized user's channel.
        $listResponse = $youtube->channels->listChannels('brandingSettings', array('mine' => 'true'));
        $responseChannel = $listResponse[0];
Exemplo n.º 30
0
/**
 * 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;
}