Upload a PHP resource stream to Google Drive

@param resource $resource
@param string $parentId
@param string $fileName
@param string $mime
@return bool|Google_Service_Drive_DriveFile
14748
protected function uploadResourceToGoogleDrive($resource, $parentId, $fileName, $srcDriveFile, $mime)
    {
        $chunkSizeBytes = $this->detectChunkSizeBytes();
        $fileSize = $this->getFileSizeBytes($resource);

        if ($fileSize <= $chunkSizeBytes) {
            // If the resource fits in a single chunk, we'll just upload it in a single request
            return $this->uploadStringToGoogleDrive(stream_get_contents($resource), $parentId, $fileName, $srcDriveFile, $mime);
        }

        $client = $this->service->getClient();
        // Call the API with the media upload, defer so it doesn't immediately return.
        $client->setDefer(true);
        $request = $this->ensureDriveFileExists('', $parentId, $fileName, $srcDriveFile, $mime);
        $client->setDefer(false);
        $media = $this->getMediaFileUpload($client, $request, $mime, $chunkSizeBytes);
        $media->setFileSize($fileSize);

        // Upload chunks until we run out of file to upload; $status will be false until the process is complete.
        $status = false;
        while (! $status && ! feof($resource)) {
            $chunk = $this->readFileChunk($resource, $chunkSizeBytes);
            $status = $media->nextChunk($chunk);
        }

        // The final value of $status will be the data from the API for the object that has been uploaded.
        return $status;
    }
548417
public function listParents($fileId, $optParams = array())
  {
    $params = array('fileId' => $fileId);
    $params = array_merge($params, $optParams);
    return $this->call('list', array($params), "Drive_ParentList");
  }
813424
public function getFileByName(
       $folderName,
       $mimeType,
       $includeTrash = false,
       \Google_Service_Drive_DriveFile $parent = null,
       $createIfNotFound = false
    ) {
        $query = 'title = \'' . $folderName . '\' and mimeType = \'' . $mimeType . '\'';
        if (!$includeTrash) {
            $query .= ' and trashed = false';
        }
        if ($parent !== null) {
            $query .= ' and \'' . $parent->getId() . '\' in parents';
        }
        $fileList = $this->service->files->listFiles(array('q' => $query));
        $folders   = $fileList->getItems();
        if (isset($folders[0])) {
            return $folders[0];
        }
        if ($createIfNotFound) {
            $this->helper->getLogger()->debug('Creating Folder ' . $folderName);
            return $this->createFolder($folderName, $parent);
        }

        return null;
    }
861231
public function request(string $resource, string $method, array $data = [], array $files = [])
	{
		if (!strpos($resource, '://')) {
			if (!strpos($resource, '.')) {
				$resource .= '.json';
			}
			$resource = self::API_URL . $resource;
		}

		foreach ($data as $key => $val) {
			if ($val === null) {
				unset($data[$key]);
			}
		}

		foreach ($files as $key => $file) {
			if (!is_file($file)) {
				throw new Exception("Cannot read the file $file. Check if file exists on disk and check its permissions.");
			}
			$data[$key] = new \CURLFile($file);
		}

		$headers = ['Expect:'];

		if ($method === 'JSONPOST') {
			$method = 'POST';
			$data = json_encode($data);
			$headers[] = 'Content-Type: application/json';

		} elseif ($method === 'GET' && $data) {
			$resource .= '?' . http_build_query($data, '', '&');
		}

		$request = OAuth\Request::from_consumer_and_token($this->consumer, $this->token, $method, $resource);
		$request->sign_request(new OAuth\SignatureMethod_HMAC_SHA1, $this->consumer, $this->token);
		$headers[] = $request->to_header();

		$options = [
			CURLOPT_URL => $resource,
			CURLOPT_HEADER => false,
			CURLOPT_RETURNTRANSFER => true,
			CURLOPT_HTTPHEADER => $headers,
		] + $this->httpOptions;
		if ($method === 'POST') {
			$options += [
				CURLOPT_POST => true,
				CURLOPT_POSTFIELDS => $data,
				CURLOPT_SAFE_UPLOAD => true,
			];
		}

		$curl = curl_init();
		curl_setopt_array($curl, $options);
		$result = curl_exec($curl);
		if (curl_errno($curl)) {
			throw new Exception('Server error: ' . curl_error($curl));
		}

		$payload = @json_decode($result, false, 128, JSON_BIGINT_AS_STRING); // intentionally @

		if ($payload === false) {
			throw new Exception('Invalid server response');
		}

		$code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
		if ($code >= 400) {
			throw new Exception(isset($payload->errors[0]->message)
				? $payload->errors[0]->message
				: "Server error #$code with answer $result",
				$code
			);
		}

		return $payload;
	}
310546
public function actionFileProvider($machine, $buildToken, $fileId)
    {
        $build = $this->ensureBuild($machine, $buildToken);
        
        if ($build) {
            if (!is_numeric($fileId)) {
                throw new ForbiddenHttpException("Invalid file id input.");
            }
            
            $file = Yii::$app->storage->getFile($fileId);
            /* @var $file \luya\admin\file\Item */
            if ($file->fileExists) {
                return Yii::$app->response->sendFile($file->serverSource, null, ['mimeType' => $file->mimeType])->send();
            }
            
            throw new NotFoundHttpException("The requested file '".$file->serverSource."' does not exist in the storage folder.");
        }
    }
145985
public static function upload($filePath, $bucket, $fileid = '', $userid = 0, $magicContext = '', $params = array()) {
        if (!file_exists($filePath)) {
            return array('httpcode' => 0, 'code' => self::IMAGE_FILE_NOT_EXISTS, 'message' => 'file '.$filePath.' not exists', 'data' => array());
        }

        return self::upload_impl($filePath, 0, $bucket, $fileid, $userid, $magicContext, $params);
    }
729590
public function upload(string $filename, $source): UploadCommand
    {
        /** @var UploadCommand $command */
        $command = $this->builder->build(UploadCommand::class);
        $command->withFilename($filename)->withSource($source);

        return $command;
    }
1262590
public function updateStream($path, $resource, $mimeType = null)
    {
        return $this->getFile($path)->update($resource, $mimeType);
    }
1321920
public function move(ResourceNode $child, ResourceNode $parent)
    {
        if ($parent === $child) {
            throw new ResourceMoveException("You cannot move a directory into itself");
        }
        $this->om->startFlushSuite();
        $this->setLastIndex($parent, $child);
        $child->setParent($parent);
        $child->setName($this->getUniqueName($child, $parent));

        if ($child->getWorkspace()->getId() !== $parent->getWorkspace()->getId()) {
            $this->updateWorkspace($child, $parent->getWorkspace());
        }
        
        $this->om->persist($child);
        $this->om->endFlushSuite();
        $this->dispatcher->dispatch('log', 'Log\LogResourceMove', array($child, $parent));

        return $child;
    }
591049
public function viewImageAction($imageId, $parentType)
    {
        if (null !== $response = $this->checkAuth($this->getAdminResources()->getResource($parentType, static::MODULE_RIGHT), array(), AccessManager::UPDATE)) {
            return $response;
        }
        $fileManager = $this->getFileManager();
        $imageModel = $fileManager->getModelInstance('image', $parentType);

        $image = $imageModel->getQueryInstance()->findPk($imageId);

        $redirectUrl = $image->getRedirectionUrl();

        return $this->render('image-edit', array(
            'imageId' => $imageId,
            'imageType' => $parentType,
            'redirectUrl' => $redirectUrl,
            'formId' => $imageModel->getUpdateFormId(),
            'breadcrumb' => $image->getBreadcrumb(
                $this->getRouter($this->getCurrentRouter()),
                $this->container,
                'images',
                $this->getCurrentEditionLocale()
            )
        ));
    }
448913
public function uploadFiles(string $filename, string $mimetype = '', string $postname = '') {

        $this->params = array_merge($this->params, $this->file($filename, $mimetype, $postname));

        return $this->header(['Content-Type' => 'multipart/form-data']);

    }
571822
public function uploadAction($folderId, Request $request)
    {
        $uploadedFile = $request->files->get('file');
        $title = $request->get('title');

        $saveMediaManager = $this->get('open_orchestra_media_admin.manager.save_media');

        if ($uploadedFile && $uploadedFile = $saveMediaManager->getFileFromChunks($uploadedFile)) {
            $siteId = $this->get('open_orchestra_backoffice.context_backoffice_manager')->getSiteId();
            $media = $saveMediaManager->initializeMediaFromUploadedFile($uploadedFile, $folderId, $siteId, $title);
            $violations = $this->get('validator')->validate($media, null, array('upload'));
            if (count($violations) !== 0) {
                return new Response(
                    implode('.', $this->getViolationsMessage($violations)),
                    403
                );
            }

            $saveMediaManager->saveMedia($media);

            return $this->get('open_orchestra_api.transformer_manager')->transform('media', $media);

        }

        return new Response('', 202);
    }
1106944
public function downloadResource (string $source, bool $full = null, string $id = null, string $mime_type = null)
    {
        $this->createFolder ('uploads/tmp');

        $fileName = $this->getFileName ($source);

        if ($fileName && $fileName != '') {

            $destination = storage_path ('app/uploads/tmp/' . $fileName);

            file_put_contents ($destination, file_get_contents ($source));

            if (filesize ($destination) <= env ('MAX_CHECKSUM_SIZE', self::MAX_CHECKSUM_SIZE)) {
                $resource = HCResources::where ('checksum', '=', hash_file ('sha256', $destination))->first ();

                if (!$this->allowDuplicates && $resource) {
                    //If duplicate found deleting downloaded file
                    \File::delete ($destination);

                    if ($full)
                        return $resource->toArray ();

                    return [
                        'id'  => $resource->id,
                        'url' => route ('resource.get', $resource->id),
                    ];
                }
            }

            if (!\File::exists ($destination)) {
                return null;
            }

            if (!$mime_type)
                $mime_type = mime_content_type ($destination);

            $file = new UploadedFile($destination, $fileName, $mime_type, filesize ($destination), null, true);

            return $this->upload ($file, $full, $id);
        }

        return null;
    }
897754
private function handleUpload(\Google_Service_Drive $service, $archive)
    {
        $file = $this->getDriveFile($archive);

        $mime = $this->getMimeType($archive);
        $file->setMimeType($mime);

        if ($this->remotePath !== '/') {
            $parent = $this->getParentFolder($service);

            if ($parent) {
                $file->setParents(array($parent));
            }
        }

        $client = $this->getClient();
        // 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 = $this->getMediaUploadFile($archive, $client, $request, $mime);

        return $this->uploadFileInChunks($archive, $media);
    }
295912
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;
    }
1340022
public static function upload(String $fileName = 'upload', String $rootDir = UPLOADS_DIR) : Bool
    {
        return Upload::start($fileName, $rootDir);
    }
1241391
protected function getMediaFileUpload($client, $request, $mime, $chunkSizeBytes)
    {
        return new Google_Http_MediaFileUpload($client, $request, $mime, null, true, $chunkSizeBytes);
    }