Opens the file
@param ClientRuntimeContext $ctx
@param $serverRelativeUrl
@return mixed|string
@throws \Exception
167831
public static function openBinary(ClientRuntimeContext $ctx, $serverRelativeUrl)
    {
        $serverRelativeUrl = rawurlencode($serverRelativeUrl);
        $url = $ctx->getServiceRootUrl() . "web/getfilebyserverrelativeurl('$serverRelativeUrl')/\$value";
        $options = new RequestOptions($url);
        $data = $ctx->executeQueryDirect($options);
        return $data;
    }
468942
@Override
  public void channelActive(final ChannelHandlerContext ctx) throws Exception {
    controlSettings = dcpControl.getControls(getServerVersion(ctx.channel())).entrySet().iterator();
    negotiate(ctx);
  }
1250519
public final static function fromPhpContext(PhpContext $phpContext)
    {
        if ($phpContext->isCliInvocation()) {
            $request = new CliRequest();
        } else {
            $contentType = (isset($_SERVER["CONTENT_TYPE"])) ? strtolower($_SERVER["CONTENT_TYPE"]) : "";

            // Special check for multipart, because the header could be multipart/form-data
            // followed by boundary
            $multipartType = "multipart/form-data";
            if (strpos($contentType, $multipartType) === 0) {
                $contentType = $multipartType;
            }

            // Firefox puts a charset on the end of the content type line
            $parts = explode(";", $contentType);
            $contentType = $parts[0];

            switch ($contentType) {
                case "application/octet-stream":
                case "image/jpeg":
                case "image/jpg":
                case "image/gif":
                case "image/png":
                    $request = new BinaryRequest();
                    break;
                case "application/json":
                    $request = new JsonRequest();
                    break;
                case "text/xml":
                case "application/xml":
                    $request = new XmlRequest();
                    break;
                case "multipart/form-data":
                    $request = new MultiPartFormDataRequest();
                    break;
                default:
                    $request = new WebRequest();
                    break;
            }
        }

        $request->phpContext = $phpContext;

        return $request;
    }
965018
function getAssociation($server_url, $handle = null)
    {
        if (!$this->active) {
            trigger_error("FileStore no longer active", E_USER_ERROR);
            return null;
        }

        if ($handle === null) {
            $handle = '';
        }

        // The filename with the empty handle is a prefix of all other
        // associations for the given server URL.
        $filename = $this->getAssociationFilename($server_url, $handle);

        if ($handle) {
            return $this->_getAssociation($filename);
        } else {
            $association_files =
                Auth_OpenID_FileStore::_listdir($this->association_dir);
            $matching_files = array();

            // strip off the path to do the comparison
            $name = basename($filename);
            foreach ($association_files as $association_file) {
                $base = basename($association_file);
                if (strpos($base, $name) === 0) {
                    $matching_files[] = $association_file;
                }
            }

            $matching_associations = array();
            // read the matching files and sort by time issued
            foreach ($matching_files as $full_name) {
                $association = $this->_getAssociation($full_name);
                if ($association !== null) {
                    $matching_associations[] = array($association->issued,
                                                     $association);
                }
            }

            $issued = array();
            $assocs = array();
            foreach ($matching_associations as $key => $assoc) {
                $issued[$key] = $assoc[0];
                $assocs[$key] = $assoc[1];
            }

            array_multisort($issued, SORT_DESC, $assocs, SORT_DESC,
                            $matching_associations);

            // return the most recently issued one.
            if ($matching_associations) {
                list(, $assoc) = $matching_associations[0];
                return $assoc;
            } else {
                return null;
            }
        }
    }
446541
private void respondWithFile(ChannelHandlerContext ctx, HttpRequest request, String requestPath)
		throws IOException, ParseException {

		// make sure we request the "index.html" in case there is a directory request
		if (requestPath.endsWith("/")) {
			requestPath = requestPath + "index.html";
		}

		if (!requestPath.contains(".")) { // we assume that the path ends in either .html or .js
			requestPath = requestPath + ".json";
		}

		// convert to absolute path
		final File file = new File(rootPath, requestPath);

		if (!file.exists()) {
			// file does not exist. Try to load it with the classloader
			ClassLoader cl = HistoryServerStaticFileServerHandler.class.getClassLoader();

			try (InputStream resourceStream = cl.getResourceAsStream("web" + requestPath)) {
				boolean success = false;
				try {
					if (resourceStream != null) {
						URL root = cl.getResource("web");
						URL requested = cl.getResource("web" + requestPath);

						if (root != null && requested != null) {
							URI rootURI = new URI(root.getPath()).normalize();
							URI requestedURI = new URI(requested.getPath()).normalize();

							// Check that we don't load anything from outside of the
							// expected scope.
							if (!rootURI.relativize(requestedURI).equals(requestedURI)) {
								LOG.debug("Loading missing file from classloader: {}", requestPath);
								// ensure that directory to file exists.
								file.getParentFile().mkdirs();
								Files.copy(resourceStream, file.toPath());

								success = true;
							}
						}
					}
				} catch (Throwable t) {
					LOG.error("error while responding", t);
				} finally {
					if (!success) {
						LOG.debug("Unable to load requested file {} from classloader", requestPath);
						HandlerUtils.sendErrorResponse(
							ctx,
							request,
							new ErrorResponseBody("File not found."),
							NOT_FOUND,
							Collections.emptyMap());
						return;
					}
				}
			}
		}

		if (!file.exists() || file.isHidden() || file.isDirectory() || !file.isFile()) {
			HandlerUtils.sendErrorResponse(
				ctx,
				request,
				new ErrorResponseBody("File not found."),
				NOT_FOUND,
				Collections.emptyMap());
			return;
		}

		if (!file.getCanonicalFile().toPath().startsWith(rootPath.toPath())) {
			HandlerUtils.sendErrorResponse(
				ctx,
				request,
				new ErrorResponseBody("File not found."),
				NOT_FOUND,
				Collections.emptyMap());
			return;
		}

		// cache validation
		final String ifModifiedSince = request.headers().get(IF_MODIFIED_SINCE);
		if (ifModifiedSince != null && !ifModifiedSince.isEmpty()) {
			SimpleDateFormat dateFormatter = new SimpleDateFormat(StaticFileServerHandler.HTTP_DATE_FORMAT, Locale.US);
			Date ifModifiedSinceDate = dateFormatter.parse(ifModifiedSince);

			// Only compare up to the second because the datetime format we send to the client
			// does not have milliseconds
			long ifModifiedSinceDateSeconds = ifModifiedSinceDate.getTime() / 1000;
			long fileLastModifiedSeconds = file.lastModified() / 1000;
			if (ifModifiedSinceDateSeconds == fileLastModifiedSeconds) {
				if (LOG.isDebugEnabled()) {
					LOG.debug("Responding 'NOT MODIFIED' for file '" + file.getAbsolutePath() + '\'');
				}

				StaticFileServerHandler.sendNotModified(ctx);
				return;
			}
		}

		if (LOG.isDebugEnabled()) {
			LOG.debug("Responding with file '" + file.getAbsolutePath() + '\'');
		}

		// Don't need to close this manually. Netty's DefaultFileRegion will take care of it.
		final RandomAccessFile raf;
		try {
			raf = new RandomAccessFile(file, "r");
		} catch (FileNotFoundException e) {
			HandlerUtils.sendErrorResponse(
				ctx,
				request,
				new ErrorResponseBody("File not found."),
				NOT_FOUND,
				Collections.emptyMap());
			return;
		}

		try {
			long fileLength = raf.length();

			HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK);
			StaticFileServerHandler.setContentTypeHeader(response, file);

			// the job overview should be updated as soon as possible
			if (!requestPath.equals("/joboverview.json")) {
				StaticFileServerHandler.setDateAndCacheHeaders(response, file);
			}
			if (HttpHeaders.isKeepAlive(request)) {
				response.headers().set(CONNECTION, HttpHeaders.Values.KEEP_ALIVE);
			}
			HttpHeaders.setContentLength(response, fileLength);

			// write the initial line and the header.
			ctx.write(response);

			// write the content.
			ChannelFuture lastContentFuture;
			if (ctx.pipeline().get(SslHandler.class) == null) {
				ctx.write(new DefaultFileRegion(raf.getChannel(), 0, fileLength), ctx.newProgressivePromise());
				lastContentFuture = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT);
			} else {
				lastContentFuture = ctx.writeAndFlush(new HttpChunkedInput(new ChunkedFile(raf, 0, fileLength, 8192)),
					ctx.newProgressivePromise());
				// HttpChunkedInput will write the end marker (LastHttpContent) for us.
			}

			// close the connection, if no keep-alive is needed
			if (!HttpHeaders.isKeepAlive(request)) {
				lastContentFuture.addListener(ChannelFutureListener.CLOSE);
			}
		} catch (Exception e) {
			raf.close();
			LOG.error("Failed to serve file.", e);
			HandlerUtils.sendErrorResponse(
				ctx,
				request,
				new ErrorResponseBody("Internal server error."),
				INTERNAL_SERVER_ERROR,
				Collections.emptyMap());
		}
	}
776461
public function connectAsync(ConnectionContext $ctx, string $header = ''): \Generator
    {
        $this->stream = yield $ctx->getStream($header);
        $this->memory_stream = fopen('php://memory', 'r+');

        return true;
    }
611367
public function url($return = null, $altRealm = null)
    {
        $useHttps = !empty($_SERVER['HTTPS']) || (!empty($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https');
        if (!is_null($return)) {
            if (!$this->validateUrl($return)) {
                throw new Exception('The return URL must be a valid URL with a URI Scheme or http or https.');
            }
        }
        else {
            if($altRealm == null)
                $return = ($useHttps ? 'https' : 'http') . '://' . $_SERVER['HTTP_HOST'] . $_SERVER['SCRIPT_NAME'];
            else
                $return = $altRealm . $_SERVER['SCRIPT_NAME'];
        }

        $params = array(
            'openid.ns'         => 'http://specs.openid.net/auth/2.0',
            'openid.mode'       => 'checkid_setup',
            'openid.return_to'  => $return,
            'openid.realm'      => $altRealm != null ? $altRealm : (($useHttps ? 'https' : 'http') . '://' . $_SERVER['HTTP_HOST']),
            'openid.identity'   => 'http://specs.openid.net/auth/2.0/identifier_select',
            'openid.claimed_id' => 'http://specs.openid.net/auth/2.0/identifier_select',
        );

        return self::$openId . '?' . http_build_query($params);
    }
998490
public function processContext($loclctx, &$activectx, $remotectxs = array())
    {
        if (is_object($loclctx)) {
            $loclctx = clone $loclctx;
        }

        if (false === is_array($loclctx)) {
            $loclctx = array($loclctx);
        }

        foreach ($loclctx as $context) {
            if (null === $context) {
                $activectx = array('@base' => $this->baseIri);
            } elseif (is_object($context)) {
                // make sure we don't modify the passed context
                $context = clone $context;

                if (property_exists($context, '@base')) {
                    if (count($remotectxs) > 0) {
                        // do nothing, @base is ignored in a remote context
                    } elseif (null === $context->{'@base'}) {
                        $activectx['@base'] = null;
                    } elseif (false === is_string($context->{'@base'})) {
                        throw new JsonLdException(
                            JsonLdException::INVALID_BASE_IRI,
                            'The value of @base must be an IRI or null.',
                            $context
                        );
                    } else {
                        $base = new IRI($context->{'@base'});
                        if (false === $base->isAbsolute()) {
                            if (null === $activectx['@base']) {
                                throw new JsonLdException(
                                    JsonLdException::INVALID_BASE_IRI,
                                    'The relative base IRI cannot be resolved to an absolute IRI.',
                                    $context
                                );
                            }

                            $activectx['@base'] = $activectx['@base']->resolve($base);
                        } else {
                            $activectx['@base'] = $base;
                        }
                    }

                    unset($context->{'@base'});
                }

                if (property_exists($context, '@vocab')) {
                    if (null === $context->{'@vocab'}) {
                        unset($activectx['@vocab']);
                    } elseif ((false === is_string($context->{'@vocab'})) ||
                              (false === strpos($context->{'@vocab'}, ':'))) {
                        throw new JsonLdException(
                            JsonLdException::INVALID_VOCAB_MAPPING,
                            'The value of @vocab must be an absolute IRI or null.invalid vocab mapping, ',
                            $context
                        );
                    } else {
                        $activectx['@vocab'] = $context->{'@vocab'};
                    }

                    unset($context->{'@vocab'});
                }

                if (property_exists($context, '@language')) {
                    if ((null !== $context->{'@language'}) && (false === is_string($context->{'@language'}))) {
                        throw new JsonLdException(
                            JsonLdException::INVALID_DEFAULT_LANGUAGE,
                            'The value of @language must be a string.',
                            $context
                        );
                    }

                    $activectx['@language'] = $context->{'@language'};
                    unset($context->{'@language'});
                }

                foreach ($context as $key => $value) {
                    unset($context->{$key});
                    unset($activectx[$key]);

                    if (in_array($key, self::$keywords)) {
                        throw new JsonLdException(JsonLdException::KEYWORD_REDEFINITION, null, $key);
                    }

                    if ((null === $value) || is_string($value)) {
                        $value = (object) array('@id' => $value);
                    } elseif (is_object($value)) {
                        $value = clone $value;    // make sure we don't modify context entries
                    } else {
                        throw new JsonLdException(JsonLdException::INVALID_TERM_DEFINITION);
                    }

                    if (property_exists($value, '@reverse')) {
                        if (property_exists($value, '@id')) {
                            throw new JsonLdException(
                                JsonLdException::INVALID_REVERSE_PROPERTY,
                                "Invalid term definition using both @reverse and @id detected",
                                $value
                            );
                        }

                        if (property_exists($value, '@container') &&
                            ('@index' !== $value->{'@container'}) &&
                            ('@set' !== $value->{'@container'})) {
                            throw new JsonLdException(
                                JsonLdException::INVALID_REVERSE_PROPERTY,
                                "Terms using the @reverse feature support only @set- and @index-containers.",
                                $value
                            );
                        }

                        $value->{'@id'} = $value->{'@reverse'};
                        $value->{'@reverse'} = true;
                    } else {
                        $value->{'@reverse'} = false;
                    }

                    if (property_exists($value, '@id')) {
                        if ((null !== $value->{'@id'}) && (false === is_string($value->{'@id'}))) {
                            throw new JsonLdException(JsonLdException::INVALID_IRI_MAPPING, null, $value->{'@id'});
                        }

                        $path = array();
                        if ($key !== $value->{'@id'}) {
                            $path[] = $key;
                        }

                        $expanded = $this->expandIri($value->{'@id'}, $activectx, false, true, $context, $path);

                        if ($value->{'@reverse'} && (false === strpos($expanded, ':'))) {
                            throw new JsonLdException(
                                JsonLdException::INVALID_IRI_MAPPING,
                                "Reverse properties must expand to absolute IRIs, \"$key\" expands to \"$expanded\"."
                            );
                        } elseif ('@context' === $expanded) {
                            throw new JsonLdException(
                                JsonLdException::INVALID_KEYWORD_ALIAS,
                                'Aliases for @context are not supported',
                                $value
                            );
                        }
                    } else {
                        $expanded = $this->expandIri($key, $activectx, false, true, $context);
                    }


                    if ((null === $expanded) || in_array($expanded, self::$keywords)) {
                        // if it's an aliased keyword or the IRI is null, we ignore all other properties
                        // TODO Should we throw an exception if there are other properties?
                        $activectx[$key] = array('@id' => $expanded, '@reverse' => false);

                        continue;
                    } elseif (false === strpos($expanded, ':')) {
                        throw new JsonLdException(
                            JsonLdException::INVALID_IRI_MAPPING,
                            "Failed to expand \"$key\" to an absolute IRI.",
                            $loclctx
                        );
                    }

                    $activectx[$key] = array('@id' => $expanded, '@reverse' => $value->{'@reverse'});

                    if (isset($value->{'@type'})) {
                        if (false === is_string($value->{'@type'})) {
                            throw new JsonLdException(JsonLdException::INVALID_TYPE_MAPPING);
                        }

                        $expanded = $this->expandIri($value->{'@type'}, $activectx, false, true, $context);

                        if (('@id' !== $expanded) && ('@vocab' !== $expanded) &&
                            ((false === strpos($expanded, ':') || (0 === strpos($expanded, '_:'))))) {
                            throw new JsonLdException(
                                JsonLdException::INVALID_TYPE_MAPPING,
                                "Failed to expand $expanded to an absolute IRI.",
                                $loclctx
                            );
                        }

                        $activectx[$key]['@type'] = $expanded;
                    } elseif (property_exists($value, '@language')) {
                        if ((false === is_string($value->{'@language'})) && (null !== $value->{'@language'})) {
                            throw new JsonLdException(
                                JsonLdException::INVALID_LANGUAGE_MAPPING,
                                'The value of @language must be a string or null.',
                                $value
                            );
                        }

                        // Note the else. Language tagging applies just to term without type coercion
                        $activectx[$key]['@language'] = $value->{'@language'};
                    }

                    if (isset($value->{'@container'})) {
                        if (in_array($value->{'@container'}, array('@list', '@set', '@language', '@index'))) {
                            $activectx[$key]['@container'] = $value->{'@container'};
                        } else {
                            throw new JsonLdException(
                                JsonLdException::INVALID_CONTAINER_MAPPING,
                                'A container mapping of ' . $value->{'@container'} . ' is not supported.'
                            );
                        }
                    }
                }
            } elseif (is_string($context)) {
                $remoteContext = new IRI($context);
                if ($remoteContext->isAbsolute()) {
                    $remoteContext = (string) $remoteContext;
                } elseif (null === $activectx['@base']) {
                    throw new JsonLdException(
                        JsonLdException::INVALID_BASE_IRI,
                        'Can not resolve the relative URL of the remote context as no base has been set: ' . $remoteContext
                    );
                } else {
                    $remoteContext = (string) $activectx['@base']->resolve($context);
                }
                if (in_array($remoteContext, $remotectxs)) {
                    throw new JsonLdException(
                        JsonLdException::RECURSIVE_CONTEXT_INCLUSION,
                        'Recursive inclusion of remote context: ' . join(' -> ', $remotectxs) . ' -> ' . $remoteContext
                    );
                }
                $remotectxs[] = $remoteContext;

                try {
                    $remoteContext = $this->loadDocument($remoteContext);
                } catch (JsonLdException $e) {
                    throw new JsonLdException(
                        JsonLdException::LOADING_REMOTE_CONTEXT_FAILED,
                        "Loading $remoteContext failed",
                        null,
                        null,
                        $e
                    );
                }

                if (is_object($remoteContext) && property_exists($remoteContext, '@context')) {
                    // TODO Use the context's IRI as base IRI when processing remote contexts (ISSUE-24)
                    $this->processContext($remoteContext->{'@context'}, $activectx, $remotectxs);
                } else {
                    throw new JsonLdException(
                        JsonLdException::INVALID_REMOTE_CONTEXT,
                        'Remote context "' . $context . '" is invalid.',
                        $remoteContext
                    );
                }
            } else {
                throw new JsonLdException(JsonLdException::INVALID_LOCAL_CONTEXT);
            }
        }
    }
293465
private static void launchServer(final String url,
                                     final CloseableHttpClient client) {
        try {
            final JDialog dialog = new JDialog();
            dialog.setSize(new java.awt.Dimension(400, 75));
            dialog.setModalityType(ModalityType.MODELESS);
            dialog.setTitle("DuraCloud Sync");
            dialog.setLocationRelativeTo(null);

            JPanel panel = new JPanel();
            final JLabel label = new JLabel("Loading...");
            final JProgressBar progress = new JProgressBar();
            progress.setStringPainted(true);

            panel.add(label);
            panel.add(progress);
            dialog.add(panel);
            dialog.setVisible(true);

            port = SyncUIConfig.getPort();
            contextPath = SyncUIConfig.getContextPath();
            Server srv = new Server(port);

            // Setup JMX
            MBeanContainer mbContainer = new MBeanContainer(
                    ManagementFactory.getPlatformMBeanServer() );
            srv.addBean( mbContainer );

            ProtectionDomain protectionDomain =
                org.duracloud.syncui.SyncUIDriver.class.getProtectionDomain();
            String warFile =
                protectionDomain.getCodeSource().getLocation().toExternalForm();

            log.debug("warfile: {}", warFile);
            WebAppContext context = new WebAppContext();
            context.setContextPath(contextPath);
            context.setWar(warFile);
            context.setExtractWAR(Boolean.TRUE);

            Configuration.ClassList classlist = Configuration.ClassList
                    .setServerDefault( srv );
            classlist.addBefore(
                    "org.eclipse.jetty.webapp.JettyWebXmlConfiguration",
                    "org.eclipse.jetty.annotations.AnnotationConfiguration" );

            context.setAttribute(
                    "org.eclipse.jetty.server.webapp.ContainerIncludeJarPattern",
                    ".*/[^/]*servlet-api-[^/]*\\.jar$|.*/javax.servlet.jsp.jstl-.*\\.jar$|.*/[^/]*taglibs.*\\.jar$" );

            srv.setHandler(context);

            new Thread(new Runnable() {
                @Override
                public void run() {
                    createSysTray(url, srv);

                    while (true) {
                        if (progress.getValue() < 100) {
                            progress.setValue(progress.getValue() + 3);
                        }

                        sleep(2000);
                        if (isAppRunning(url, client)) {
                            break;
                        }
                    }

                    progress.setValue(100);

                    label.setText("Launching browser...");
                    launchBrowser(url);
                    dialog.setVisible(false);
                }
            }).start();

            srv.start();

            srv.join();
        } catch (Exception e) {
            log.error("Error launching server: " + e.getMessage(), e);
        }
    }
58725
public function execute($actionContext) {
        if (($path = PathUtility::getFilePath($this->path)) === false) {
            throw new \Exception('File "' . $this->path . '" not found.');
        }

        if (empty($this->contentType) && function_exists('finfo_open') && ($fi = finfo_file(finfo_open(\FILEINFO_MIME_TYPE), $path) !== false)) {
            $this->contentType = $fi;
        }

        $response = $actionContext->getHttpContext()->getResponse();
        $response->addHeader('Content-Type', (!empty($this->contentType) ? $this->contentType : 'application/octet-stream'));
        $response->addHeader('Content-Length', filesize($path));

        if (!empty($this->downloadName)) {
            $response->addHeader('Content-Disposition', 'attachment; filename="' . $this->downloadName . '"');
        }

        $response->writeFile($path);

        $response->end();
    }
139600
public function exceptionToHttpResponse( Exception $e, TOGoS_Action $action=null, $ctx=null ) {
		$userIsAuthenticated = ($ctx and method_exists($ctx,'userIsAuthenticated')) ? $ctx->userIsAuthenticated() : false;
		return EarthIT_CMIPREST_Util::exceptionalNormalJsonHttpResponse($e, $userIsAuthenticated, array(
			EarthIT_CMIPREST_Util::BASIC_WWW_AUTHENTICATION_REALM => $this->basicWwwAuthenticationRealm
		));
	}
483739
@Override
  public Resource createRelative(String relativePath) {
    String pathToUse = StringUtils.applyRelativePath(this.path, relativePath);
    return new ServletContextResource(this.servletContext, pathToUse);
  }
1157509
public function initFromUrl($url)
    {
        
        $options = [
            'http' => [
                'method'=>"GET",
                'header'=>"Accept-language: en\r\n".
                "User-Agent: Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.2 (KHTML, like Gecko) Chrome/22.0.1216.0 Safari/537.2\r\n"
          ]
        ];
        
        $context  = stream_context_create($options);
        

        if ($data = @file_get_contents($url, false, $context)) {
            return $this->initFromBinary($data);
        }

        throw new \Intervention\Image\Exception\NotReadableException(
            "Unable to init from given url (".$url.")."
        );
    }
681025
@AroundInvoke
    public Object intercept(final InvocationContext ctx)
            throws JaxRsResponseException {
        try {
            return ctx.proceed();
        }
        catch (final Exception theException) {
            final AbstractJaxRsProvider theServer = (AbstractJaxRsProvider) ctx.getTarget();
            throw convertException(theServer, theException);
        }
    }
732976
public function get($remFile, $locFile)
    {
        if (is_string($locFile)) {
            set_error_handler(function () {});
            $fileHandle = fopen($locFile, 'w+b');
            restore_error_handler();
        } else if (is_resource($locFile)) {
            $fileHandle = $locFile;
        } else {
            throw new InvalidArgumentException('Invalid local file');
        }

        if ($fileHandle === false) {
            throw new RuntimeException('File open error');
        }

        $writeBinn = new BinnList;

        $writeBinn->addUint8(self::FSERV_FILESEND);
        $writeBinn->addUint8(self::FSERV_DOWNLOAD_FR_SERVER);
        $writeBinn->addStr($remFile);

        $read = $this->writeAndReadSocket($writeBinn->serialize());

        $readBinn = new BinnList;
        $readBinn->binnOpen($read);
        $results = $readBinn->unserialize();

        if ($results[0] == self::FSERV_STATUS_OK) {
            throw new RuntimeException('Unexpected `OK` status. Expected `ready to transfer`');
        } else if ($results[0] != self::FSERV_STATUS_FILE_TRANSFER_READY) {
            throw new RuntimeException('Couldn\'t upload file: ' . isset($results[1]) ? $results[1] : 'Unknown');
        }

        $this->writeSocket(self::SOCKET_MSG_ENDL);

        $filesize = $results[2];
        $writed = 0;

        while($writed < $filesize) {
            if ($filesize - $writed > $this->maxBufsize) {
                $readlen = $this->maxBufsize;
            }
            else {
                $readlen = $filesize - $writed;
            }

            $socketRead = $this->readSocket($readlen, true);

            $writed += fwrite($fileHandle, $socketRead, $readlen);
        }

        if (is_resource($locFile)) {
            rewind($fileHandle);
            return $fileHandle;
        } else {
            fclose($fileHandle);
            return true;
        }
    }
1103143
public static String casOAuthCallbackUrl(final String serverPrefixUrl) {
        return serverPrefixUrl.concat(OAuth20Constants.BASE_OAUTH20_URL + '/' + OAuth20Constants.CALLBACK_AUTHORIZE_URL);
    }
712837
public function connectAsync(ConnectionContext $ctx): \Generator
    {
        $this->write_hash = null;
        $this->write_check_after = 0;
        $this->write_check_pos = 0;
        $this->read_hash = null;
        $this->read_check_after = 0;
        $this->read_check_pos = 0;

        $this->stream = yield $ctx->getStream();
    }