Example #1
0
 public function send(StreamInterface $stream)
 {
     if (!$stream->isWritable()) {
         throw new \InvalidArgumentException('Output stream must be writable');
     }
     $stream->write($this->contents);
 }
Example #2
0
    public function writeText(StreamInterface $stream)
    {
        $text = $this->text;
        $menu = $this->menu;
        $token = $this->requestToken;
        $stream->write(<<<HTML
            <form method="post" action="{$text->e($text->getUrlPage("rename_menu", $menu->getId()))}">
                <p>
                    {$text->t("main.fields_required")}
                </p>
                <p>
                    <label for="menu_name">
                        {$text->t("links.menu.name")}: <span class="required">*</span>
                    </label> <br />
                    <input type="text" name="menu_name" id="menu_name" value="{$text->e($menu->getName())}" size="20"
                            maxlength="{$text->e(MenuRepository::NAME_MAX_LENGTH)}" />
                </p>
                <p>
                    <input type="hidden" name="{$text->e(RequestToken::FIELD_NAME)}" value="{$text->e($token->getTokenString())}" />
                    <input class="button primary_button" type="submit" value="{$text->t("editor.save")}" />
                    <a class="button" href="{$text->e($text->getUrlPage("edit_menu", $menu->getId()))}">
                        {$text->t("main.cancel")}
                    </a>
                </p>
            </form>
HTML
);
    }
Example #3
0
    public function writeText(StreamInterface $stream)
    {
        $text = $this->text;
        $stream->write(<<<HTML
            <p>
                {$text->t("main.fields_required")}
            </p>
            <form method="post" action="{$text->url("edit_category", $this->category->getId())}">
                <p>
                    <label for="category_name">{$text->t("categories.name")}:</label>
                    <span class="required">*</span>
                    <br />
                    <input type="text" id="category_name" name="category_name"
                        maxlength="{$text->e(CategoryRepository::NAME_MAX_LENGTH)}"
                        value="{$text->e($this->category->getName())}" />
                </p>
                <p>
                    <label for="category_description">{$text->t("categories.description")}:</label>
                    <br />
                    {$this->richEditor->getEditor("category_description", $this->category->getDescriptionHtml())}
                </p>
                <p>
                    <input type="hidden" name="{$text->e(RequestToken::FIELD_NAME)}"
                        value="{$text->e($this->requestToken->getTokenString())}" />
                    <input type="submit" class="button primary_button" value="{$text->t("editor.save")}" />
                    <a class="button" href="{$text->url("category_list")}">
                        {$text->t("main.cancel")}
                    </a>
                </p>
            </form>
HTML
);
    }
Example #4
0
 public function send(StreamInterface $stream)
 {
     if (!$stream->isWritable()) {
         throw new \InvalidArgumentException('Output stream must be writable');
     }
     if (is_array($this->callback)) {
         $ref = (new \ReflectionClass(is_object($this->callback[0]) ? get_class($this->callback[0]) : $this->callback[0]))->getMethod($this->callback[1]);
     } elseif (is_object($this->callback) && !$this->callback instanceof \Closure) {
         $ref = new \ReflectionMethod(get_class($this->callback), '__invoke');
     } else {
         $ref = new \ReflectionFunction($this->callback);
     }
     if ($ref->isGenerator()) {
         foreach (call_user_func($this->callback) as $chunk) {
             $stream->write($chunk);
         }
         return;
     }
     foreach ($ref->getParameters() as $param) {
         if (NULL !== ($type = $param->getClass())) {
             if ($type->name === StreamInterface::class || $type->implementsInterface(StreamInterface::class)) {
                 call_user_func($this->callback, $stream);
                 return;
             }
         }
         break;
     }
     $stream->write((string) call_user_func($this->callback));
 }
 /**
  * Retrieve a single line from the stream.
  *
  * Retrieves a line from the stream; a line is defined as a sequence of
  * characters ending in a CRLF sequence.
  *
  * @param StreamInterface $stream
  * @return string
  * @throws UnexpectedValueException if the sequence contains a CR or LF in
  *     isolation, or ends in a CR.
  */
 protected static function getLine(StreamInterface $stream)
 {
     $line = '';
     $crFound = false;
     while (!$stream->eof()) {
         $char = $stream->read(1);
         if ($crFound && $char === self::LF) {
             $crFound = false;
             break;
         }
         // CR NOT followed by LF
         if ($crFound && $char !== self::LF) {
             throw new UnexpectedValueException('Unexpected carriage return detected');
         }
         // LF in isolation
         if (!$crFound && $char === self::LF) {
             throw new UnexpectedValueException('Unexpected line feed detected');
         }
         // CR found; do not append
         if ($char === self::CR) {
             $crFound = true;
             continue;
         }
         // Any other character: append
         $line .= $char;
     }
     // CR found at end of stream
     if ($crFound) {
         throw new UnexpectedValueException("Unexpected end of headers");
     }
     return $line;
 }
Example #6
0
    public function writeText(StreamInterface $stream)
    {
        $text = $this->text;
        foreach ($this->themeInfos as $themeInfo) {
            $stream->write(<<<HTML
                <h3>{$text->e($themeInfo->getDisplayName())}</h3>
                <p>
                    {$text->e($themeInfo->getDescription())}
                    {$text->tReplaced("themes.created_by", '<a href="' . $text->e($themeInfo->getAuthorWebsite()) . '">' . $text->e($themeInfo->getAuthor()) . '</a>')}.
                    <a href="{$text->e($themeInfo->getThemeWebsite())}" class="arrow">{$this->text->t("themes.view_more_information")}</a>
                </p>
                <p>
                    <form method="post" action="{$text->url("switch_theme")}">
                        <input type="hidden" name="theme" value="{$text->e($themeInfo->getDirectoryName())}" />
                        <input type="hidden" name="{$text->e(RequestToken::FIELD_NAME)}" value="{$text->e($this->requestToken->getTokenString())}" />
                        <input type="submit" class="button" value="{$text->t("themes.switch_to_this")}" />
                    </form>
                    </a>
                </p>
HTML
);
        }
        $stream->write(<<<HTML
            <p>
                <a class="arrow" href="{$text->url("admin")}">{$text->t("main.admin")}</a>         
            </p>
HTML
);
    }
 /**
  * Determines if the body should be uploaded using PutObject or the
  * Multipart Upload System. It also modifies the passed-in $body as needed
  * to support the upload.
  *
  * @param StreamInterface $body      Stream representing the body.
  * @param integer             $threshold Minimum bytes before using Multipart.
  *
  * @return bool
  */
 private function requiresMultipart(StreamInterface &$body, $threshold)
 {
     // If body size known, compare to threshold to determine if Multipart.
     if ($body->getSize() !== null) {
         return $body->getSize() >= $threshold;
     }
     /**
      * Handle the situation where the body size is unknown.
      * Read up to 5MB into a buffer to determine how to upload the body.
      * @var StreamInterface $buffer
      */
     $buffer = Psr7\stream_for();
     Psr7\copy_to_stream($body, $buffer, MultipartUploader::PART_MIN_SIZE);
     // If body < 5MB, use PutObject with the buffer.
     if ($buffer->getSize() < MultipartUploader::PART_MIN_SIZE) {
         $buffer->seek(0);
         $body = $buffer;
         return false;
     }
     // If body >= 5 MB, then use multipart. [YES]
     if ($body->isSeekable()) {
         // If the body is seekable, just rewind the body.
         $body->seek(0);
     } else {
         // If the body is non-seekable, stitch the rewind the buffer and
         // the partially read body together into one stream. This avoids
         // unnecessary disc usage and does not require seeking on the
         // original stream.
         $buffer->seek(0);
         $body = new Psr7\AppendStream([$buffer, $body]);
     }
     return true;
 }
Example #8
0
 /**
  * Append another input stream.
  * 
  * @param StreamInterface $stream
  * 
  * @throws \InvalidArgumentException When the given stream is not readable.
  */
 public function appendStream(StreamInterface $stream)
 {
     if (!$stream->isReadable()) {
         throw new \InvalidArgumentException('Appended input stream must be readable');
     }
     $this->streams[] = $stream;
 }
 /**
  * {@inheritdoc}
  *
  * @param StreamInterface $content
  *   (Optional) The content to override the input stream with. This is mainly
  *   here for testing purposes.
  *
  */
 public static function fromGlobals(array $server = null, array $query = null, array $body = null, array $cookies = null, array $files = null, StreamInterface $content = null)
 {
     $server = static::normalizeServer($server ?: $_SERVER);
     $files = static::normalizeFiles($files ?: $_FILES);
     $headers = static::marshalHeaders($server);
     // static::get() has a default parameter, however, if the header is set but
     // the value is NULL, e.g. during a drush operation, the NULL result is
     // returned, instead of the default.
     $method = strtoupper(static::get('REQUEST_METHOD', $server) ?: 'GET');
     $request = new JsonRequest($server, $files, static::marshalUriFromServer($server, $headers), $method, $content ?: 'php://input', $headers);
     $is_json = strpos(static::get('CONTENT_TYPE', $server), 'application/json') !== FALSE;
     $vars_in_body = in_array($method, ['PUT', 'POST', 'PATCH', 'DELETE']);
     if ($vars_in_body) {
         $data = $content ? $content->getContents() : file_get_contents('php://input');
         $body = $body ?: [];
         $new = [];
         if ($is_json) {
             $new = json_decode($data, TRUE);
         } else {
             parse_str($data, $new);
         }
         // Merge in data to $body.
         $body = array_merge($body, $new);
     }
     return $request->withCookieParams($cookies ?: $_COOKIE)->withQueryParams($query ?: $_GET)->withParsedBody($body ?: $_POST);
 }
Example #10
0
 /**
  * StreamRange constructor.
  * @param StreamInterface $stream
  * @param string $range
  * @throws
  */
 public function __construct(StreamInterface $stream, $range)
 {
     $range = trim($range);
     $length = $stream->getSize();
     if (preg_match('/^(\\d+)\\-$/', $range, $match)) {
         $this->firstPos = intval($match[1]);
         if ($this->firstPos > $length - 1) {
             throw new StreamRangeException('HTTP/1.1 416 Requested Range Not Satisfiable');
         }
         $this->lastPos = $length - 1;
     } elseif (preg_match('/^(\\d+)\\-(\\d+)$/', $range, $match)) {
         $this->firstPos = intval($match[1]);
         $this->lastPos = intval($match[2]);
         if ($this->lastPos < $this->firstPos || $this->lastPos > $length - 1) {
             throw new StreamRangeException('HTTP/1.1 416 Requested Range Not Satisfiable');
         }
     } elseif (preg_match('/^\\-(\\d+)$/', $range, $match)) {
         $suffixLength = intval($match[1]);
         if ($suffixLength === 0 || $suffixLength > $length) {
             throw new StreamRangeException('HTTP/1.1 416 Requested Range Not Satisfiable');
         }
         $this->firstPos = $length - $suffixLength;
         $this->lastPos = $length - 1;
     } else {
         throw new StreamRangeException('HTTP/1.1 416 Requested Range Not Satisfiable');
     }
 }
 /**
  * @test
  */
 public function toolbarIsAppendedWhenContentTypeIsHtml()
 {
     $this->body->expects($this->once())->method('isWritable')->will($this->returnValue(true));
     $this->body->expects($this->once())->method('write');
     $this->response->expects($this->once())->method('getHeader')->will($this->returnValue(['text/html']));
     $this->middleware->__invoke($this->request, $this->response);
 }
Example #12
0
    public function writeText(StreamInterface $stream)
    {
        $text = $this->text;
        $editorHtml = $this->installedWidgets->getEditor($this->editWidget);
        $actionUrl = $text->getUrlPage("edit_widget", $this->editWidget->getId());
        $documentEditUrl = $text->getUrlPage("edit_document", $this->editWidget->getDocumentId());
        $tokenNameHtml = $text->e(RequestToken::FIELD_NAME);
        $tokenValueHtml = $text->e($this->requestToken->getTokenString());
        $stream->write(<<<EDITOR
            <p>{$this->text->t("main.fields_required")}</p>
            <form method="POST" action="{$text->e($actionUrl)}">
                {$editorHtml}

                <p>
                    <input type="hidden" name="{$tokenNameHtml}" value="{$tokenValueHtml}" />
                    <input type="hidden" name="document_id" value="{$this->editWidget->getDocumentId()}" />
                    <input type="hidden" name="directory_name" value="{$this->editWidget->getDirectoryName()}" />
                    <input class="button primary_button" 
                        type="submit" 
                        name="submit"
                        value="{$this->text->t("editor.save")}" />
                    <a class="button" href="{$text->e($documentEditUrl)}">
                        {$this->text->t("main.cancel")}
                    </a>
                </p>
            </form>
EDITOR
);
    }
 public function writeUnauthorized()
 {
     $this->response = $this->response->withStatus(401);
     $apiResponse = new ApiResponse();
     $apiResponse->setStatusFail();
     $apiResponse->setData("Unauthorized");
     $this->body->write($apiResponse->toJSON());
 }
Example #14
0
 public function writeText(StreamInterface $stream)
 {
     if ($this->newUser === null) {
         $stream->write($this->getErrorText());
     } else {
         $stream->write($this->getSuccessText());
     }
 }
Example #15
0
 public function send(StreamInterface $stream)
 {
     if (!$stream->isWritable()) {
         throw new \InvalidArgumentException('Output stream must be writable');
     }
     while (!$this->stream->eof()) {
         $stream->write($this->stream->read(4096));
     }
 }
Example #16
0
 public function writeText(StreamInterface $stream)
 {
     // Link to manage widgets
     $stream->write($this->getWidgetsEditLinks());
     // Output widgets
     foreach ($this->placedWidgets as $widget) {
         $this->widgetLoader->writeOutput($stream, $widget);
     }
 }
Example #17
0
 /**
  * @param StreamInterface $stream
  */
 protected function body($stream)
 {
     if ($stream instanceof Messages\Stream\Implementation) {
         $stream->rewind();
         $this->fpassthru($stream->resource());
     } else {
         $this->output((string) $stream);
     }
 }
Example #18
0
 /**
  * Append stream to stack.
  *
  * @param  StreamInterface $stream
  * @return self
  */
 public function add(StreamInterface $stream)
 {
     if (!$stream->isReadable()) {
         throw new \InvalidArgumentException('Each stream must be readable');
     }
     $this->seekable = $stream->isSeekable() && $this->seekable;
     $this->streams[] = $stream;
     return $this;
 }
Example #19
0
 public function writeText(StreamInterface $stream)
 {
     foreach ($this->comments as $comment) {
         $stream->write($this->getSingleComment($comment));
     }
     if (count($this->comments) == 0) {
         $stream->write("<p><em>" . $this->text->t("errors.nothing_found") . "</em></p>\n");
     }
 }
Example #20
0
 /**
  * Copy stream to another stream.
  *
  * @param   StreamInterface  $src   Source stream.
  * @param   StreamInterface  $dest  Target stream.
  *
  * @return  void
  */
 public static function copy(StreamInterface $src, StreamInterface $dest)
 {
     if ($src->isSeekable()) {
         $src->rewind();
     }
     while (!$src->eof()) {
         $dest->write($src->read(4096));
     }
 }
Example #21
0
 public function __construct($filename, StreamInterface $stream, $mediaType = NULL)
 {
     if (!$stream->isReadable()) {
         throw new \InvalidArgumentException(sprintf('Input stream of file "%s" must be readable'));
     }
     $this->fileName = new UnicodeString($filename);
     $this->stream = $stream;
     $this->mediaType = $mediaType === NULL ? Filesystem::guessMimeTypeFromFilename($this->fileName) : new MediaType($mediaType);
 }
 /**
  * {@inheritDoc}
  */
 public function __invoke(StreamInterface $stream)
 {
     $request = \GuzzleHttp\Psr7\parse_request($stream->getContents());
     $response = $this->run($request);
     if ($this->getAssertionCallback()) {
         call_user_func($this->getAssertionCallback(), $request);
     }
     return \GuzzleHttp\Psr7\stream_for(\GuzzleHttp\Psr7\str($response));
 }
Example #23
0
 public function writeText(StreamInterface $stream, Website $website, $id, $data)
 {
     if (!isset($data["text"]) || !isset($data["title"])) {
         return;
     }
     if (strLen($data["title"]) > 0) {
         $stream->write("<h2>" . htmlSpecialChars($data["title"]) . "</h2>\n");
     }
     $stream->write($data["text"]);
 }
 /**
  * Parse a response from a stream.
  *
  * @param StreamInterface $stream
  * @return ResponseInterface
  * @throws InvalidArgumentException when the stream is not readable.
  * @throws UnexpectedValueException when errors occur parsing the message.
  */
 public static function fromStream(StreamInterface $stream)
 {
     if (!$stream->isReadable() || !$stream->isSeekable()) {
         throw new InvalidArgumentException('Message stream must be both readable and seekable');
     }
     $stream->rewind();
     list($version, $status, $reasonPhrase) = self::getStatusLine($stream);
     list($headers, $body) = self::splitStream($stream);
     return (new Response($body, $status, $headers))->withProtocolVersion($version)->withStatus((int) $status, $reasonPhrase);
 }
Example #25
0
 public function writeText(StreamInterface $stream, Website $website, $id, $data)
 {
     $title = htmlSpecialChars($data["title"]);
     $amount = (int) $data["amount"];
     $commentLookup = new CommentRepository($website->getDatabase());
     $latestComments = $commentLookup->getCommentsLatest($amount);
     $view = new CommentsSmallTemplate($website->getText(), $latestComments);
     $stream->write('<h2>' . $title . "</h2>\n");
     $view->writeText($stream);
 }
Example #26
0
 function withBody(StreamInterface $body) : self
 {
     if ($this->stream === $body) {
         return $this;
     }
     $new = clone $this;
     $new->stream = $body;
     $new->body = $body->extract();
     return $new;
 }
 private function cropContent(StreamInterface $stream = null)
 {
     if (null === $stream) {
         return '';
     }
     if ($stream->getSize() <= $this->maxBodySize) {
         return (string) $stream;
     }
     $stream->seek(0);
     return '(partial content)' . $stream->read($this->maxBodySize) . '(...)';
 }
Example #28
0
 /**
  * Add a stream to the AppendStream
  *
  * @param StreamInterface $stream Stream to append. Must be readable.
  *
  * @throws \InvalidArgumentException if the stream is not readable
  */
 public function addStream(StreamInterface $stream)
 {
     if (!$stream->isReadable()) {
         throw new \InvalidArgumentException('Each stream must be readable');
     }
     // The stream is only seekable if all streams are seekable
     if (!$stream->isSeekable()) {
         $this->seekable = false;
     }
     $this->streams[] = $stream;
 }
    public function writeText(StreamInterface $stream)
    {
        $text = $this->text;
        $stream->write(<<<HTML
            <p>{$text->t("install.no_tables_yet")}</p>
            <a href="{$text->e($text->getUrlPage("install", null, ["action" => "install_database"]))}" class="button primary_button">
                {$text->t("install.create_tables")}
            </a>
HTML
);
    }
 /**
  * Deserialize a request stream to a request instance.
  *
  * @param StreamInterface $stream
  * @return Request
  * @throws UnexpectedValueException when errors occur parsing the message.
  */
 public static function fromStream(StreamInterface $stream)
 {
     if (!$stream->isReadable() || !$stream->isSeekable()) {
         throw new InvalidArgumentException('Message stream must be both readable and seekable');
     }
     $stream->rewind();
     list($method, $requestTarget, $version) = self::getRequestLine($stream);
     $uri = self::createUriFromRequestTarget($requestTarget);
     list($headers, $body) = self::splitStream($stream);
     return (new Request($uri, $method, $body, $headers))->withProtocolVersion($version)->withRequestTarget($requestTarget);
 }