repo
stringlengths
7
63
file_url
stringlengths
81
284
file_path
stringlengths
5
200
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:02:33
2026-01-05 05:24:06
truncated
bool
2 classes
saxap/clean-wp-template
https://github.com/saxap/clean-wp-template/blob/30d352222831f098d0f50785f5aa453744b2e07c/your-clean-template-3/functions.php
your-clean-template-3/functions.php
<?php /** * Функции шаблона (function.php) * @package WordPress * @subpackage your-clean-template-3 */ add_theme_support('title-tag'); // теперь тайтл управляется самим вп register_nav_menus(array( // Регистрируем 2 меню 'top' => 'Верхнее', // Верхнее 'bottom' => 'Внизу' // Внизу )); add_theme_support('post-thumbnails'); // включаем поддержку миниатюр set_post_thumbnail_size(250, 150); // задаем размер миниатюрам 250x150 add_image_size('big-thumb', 400, 400, true); // добавляем еще один размер картинкам 400x400 с обрезкой register_sidebar(array( // регистрируем левую колонку, этот кусок можно повторять для добавления новых областей для виджитов 'name' => 'Сайдбар', // Название в админке 'id' => "sidebar", // идентификатор для вызова в шаблонах 'description' => 'Обычная колонка в сайдбаре', // Описалово в админке 'before_widget' => '<div id="%1$s" class="widget %2$s">', // разметка до вывода каждого виджета 'after_widget' => "</div>\n", // разметка после вывода каждого виджета 'before_title' => '<span class="widgettitle">', // разметка до вывода заголовка виджета 'after_title' => "</span>\n", // разметка после вывода заголовка виджета )); if (!class_exists('clean_comments_constructor')) { // если класс уже есть в дочерней теме - нам не надо его определять class clean_comments_constructor extends Walker_Comment { // класс, который собирает всю структуру комментов public function start_lvl( &$output, $depth = 0, $args = array()) { // что выводим перед дочерними комментариями $output .= '<ul class="children">' . "\n"; } public function end_lvl( &$output, $depth = 0, $args = array()) { // что выводим после дочерних комментариев $output .= "</ul><!-- .children -->\n"; } protected function comment( $comment, $depth, $args ) { // разметка каждого комментария, без закрывающего </li>! $classes = implode(' ', get_comment_class()).($comment->comment_author_email == get_the_author_meta('email') ? ' author-comment' : ''); // берем стандартные классы комментария и если коммент пренадлежит автору поста добавляем класс author-comment echo '<li id="comment-'.get_comment_ID().'" class="'.$classes.' media">'."\n"; // родительский тэг комментария с классами выше и уникальным якорным id echo '<div class="media-left">'.get_avatar($comment, 64, '', get_comment_author(), array('class' => 'media-object'))."</div>\n"; // покажем аватар с размером 64х64 echo '<div class="media-body">'; echo '<span class="meta media-heading">Автор: '.get_comment_author()."\n"; // имя автора коммента //echo ' '.get_comment_author_email(); // email автора коммента, плохой тон выводить почту echo ' '.get_comment_author_url(); // url автора коммента echo ' Добавлено '.get_comment_date('F j, Y в H:i')."\n"; // дата и время комментирования if ( '0' == $comment->comment_approved ) echo '<br><em class="comment-awaiting-moderation">Ваш комментарий будет опубликован после проверки модератором.</em>'."\n"; // если комментарий должен пройти проверку echo "</span>"; comment_text()."\n"; // текст коммента $reply_link_args = array( // опции ссылки "ответить" 'depth' => $depth, // текущая вложенность 'reply_text' => 'Ответить', // текст 'login_text' => 'Вы должны быть залогинены' // текст если юзер должен залогинеться ); echo get_comment_reply_link(array_merge($args, $reply_link_args)); // выводим ссылку ответить echo '</div>'."\n"; // закрываем див } public function end_el( &$output, $comment, $depth = 0, $args = array() ) { // конец каждого коммента $output .= "</li><!-- #comment-## -->\n"; } } } if (!function_exists('pagination')) { // если ф-я уже есть в дочерней теме - нам не надо её определять function pagination() { // функция вывода пагинации global $wp_query; // текущая выборка должна быть глобальной $big = 999999999; // число для замены $links = paginate_links(array( // вывод пагинации с опциями ниже 'base' => str_replace($big,'%#%',esc_url(get_pagenum_link($big))), // что заменяем в формате ниже 'format' => '?paged=%#%', // формат, %#% будет заменено 'current' => max(1, get_query_var('paged')), // текущая страница, 1, если $_GET['page'] не определено 'type' => 'array', // нам надо получить массив 'prev_text' => 'Назад', // текст назад 'next_text' => 'Вперед', // текст вперед 'total' => $wp_query->max_num_pages, // общие кол-во страниц в пагинации 'show_all' => false, // не показывать ссылки на все страницы, иначе end_size и mid_size будут проигнорированны 'end_size' => 15, // сколько страниц показать в начале и конце списка (12 ... 4 ... 89) 'mid_size' => 15, // сколько страниц показать вокруг текущей страницы (... 123 5 678 ...). 'add_args' => false, // массив GET параметров для добавления в ссылку страницы 'add_fragment' => '', // строка для добавления в конец ссылки на страницу 'before_page_number' => '', // строка перед цифрой 'after_page_number' => '' // строка после цифры )); if( is_array( $links ) ) { // если пагинация есть echo '<ul class="pagination">'; foreach ( $links as $link ) { if ( strpos( $link, 'current' ) !== false ) echo "<li class='active'>$link</li>"; // если это активная страница else echo "<li>$link</li>"; } echo '</ul>'; } } } add_action('wp_footer', 'add_scripts'); // приклеем ф-ю на добавление скриптов в футер if (!function_exists('add_scripts')) { // если ф-я уже есть в дочерней теме - нам не надо её определять function add_scripts() { // добавление скриптов if(is_admin()) return false; // если мы в админке - ничего не делаем wp_deregister_script('jquery'); // выключаем стандартный jquery wp_enqueue_script('jquery','//ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js','','',true); // добавляем свой wp_enqueue_script('bootstrap', get_template_directory_uri().'/js/bootstrap.min.js','','',true); // бутстрап wp_enqueue_script('main', get_template_directory_uri().'/js/main.js','','',true); // и скрипты шаблона } } add_action('wp_print_styles', 'add_styles'); // приклеем ф-ю на добавление стилей в хедер if (!function_exists('add_styles')) { // если ф-я уже есть в дочерней теме - нам не надо её определять function add_styles() { // добавление стилей if(is_admin()) return false; // если мы в админке - ничего не делаем wp_enqueue_style( 'bs', get_template_directory_uri().'/css/bootstrap.min.css' ); // бутстрап wp_enqueue_style( 'main', get_template_directory_uri().'/style.css' ); // основные стили шаблона } } if (!class_exists('bootstrap_menu')) { class bootstrap_menu extends Walker_Nav_Menu { // внутри вывод private $open_submenu_on_hover; // параметр который будет определять раскрывать субменю при наведении или оставить по клику как в стандартном бутстрапе function __construct($open_submenu_on_hover = true) { // в конструкторе $this->open_submenu_on_hover = $open_submenu_on_hover; // запишем параметр раскрывания субменю } function start_lvl(&$output, $depth = 0, $args = array()) { // старт вывода подменюшек $output .= "\n<ul class=\"dropdown-menu\">\n"; // ул с классом } function start_el(&$output, $item, $depth = 0, $args = array(), $id = 0) { // старт вывода элементов $item_html = ''; // то что будет добавлять parent::start_el($item_html, $item, $depth, $args); // вызываем стандартный метод родителя if ( $item->is_dropdown && $depth === 0 ) { // если элемент содержит подменю и это элемент первого уровня if (!$this->open_submenu_on_hover) $item_html = str_replace('<a', '<a class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false"', $item_html); // если подменю не будет раскрывать при наведении надо добавить стандартные атрибуты бутстрапа для раскрытия по клику $item_html = str_replace('</a>', ' <b class="caret"></b></a>', $item_html); // ну это стрелочка вниз } $output .= $item_html; // приклеиваем теперь } function display_element($element, &$children_elements, $max_depth, $depth = 0, $args, &$output) { // вывод элемента if ( $element->current ) $element->classes[] = 'active'; // если элемент активный надо добавить бутстрап класс для подсветки $element->is_dropdown = !empty( $children_elements[$element->ID] ); // если у элемента подменю if ( $element->is_dropdown ) { // если да if ( $depth === 0 ) { // если li содержит субменю 1 уровня $element->classes[] = 'dropdown'; // то добавим этот класс if ($this->open_submenu_on_hover) $element->classes[] = 'show-on-hover'; // если нужно показывать субменю по хуверу } elseif ( $depth === 1 ) { // если li содержит субменю 2 уровня $element->classes[] = 'dropdown-submenu'; // то добавим этот класс, стандартный бутстрап не поддерживает подменю больше 2 уровня по этому эту ситуацию надо будет разрешать отдельно } } parent::display_element($element, $children_elements, $max_depth, $depth, $args, $output); // вызываем стандартный метод родителя } } } if (!function_exists('content_class_by_sidebar')) { // если ф-я уже есть в дочерней теме - нам не надо её определять function content_class_by_sidebar() { // функция для вывода класса в зависимости от существования виджетов в сайдбаре if (is_active_sidebar( 'sidebar' )) { // если есть echo 'col-sm-9'; // пишем класс на 80% ширины } else { // если нет echo 'col-sm-12'; // контент на всю ширину } } } ?>
php
MIT
30d352222831f098d0f50785f5aa453744b2e07c
2026-01-05T05:18:29.067673Z
false
saxap/clean-wp-template
https://github.com/saxap/clean-wp-template/blob/30d352222831f098d0f50785f5aa453744b2e07c/your-clean-template-3/index.php
your-clean-template-3/index.php
<?php /** * Главная страница (index.php) * @package WordPress * @subpackage your-clean-template-3 */ get_header(); // подключаем header.php ?> <section> <div class="container"> <div class="row"> <div class="<?php content_class_by_sidebar(); // функция подставит класс в зависимости от того есть ли сайдбар, лежит в functions.php ?>"> <h1><?php // заголовок архивов if (is_day()) : printf('Daily Archives: %s', get_the_date()); // если по дням elseif (is_month()) : printf('Monthly Archives: %s', get_the_date('F Y')); // если по месяцам elseif (is_year()) : printf('Yearly Archives: %s', get_the_date('Y')); // если по годам else : 'Archives'; endif; ?></h1> <?php if (have_posts()) : while (have_posts()) : the_post(); // если посты есть - запускаем цикл wp ?> <?php get_template_part('loop'); // для отображения каждой записи берем шаблон loop.php ?> <?php endwhile; // конец цикла else: echo '<p>Нет записей.</p>'; endif; // если записей нет, напишим "простите" ?> <?php pagination(); // пагинация, функция нах-ся в function.php ?> </div> <?php get_sidebar(); // подключаем sidebar.php ?> </div> </div> </section> <?php get_footer(); // подключаем footer.php ?>
php
MIT
30d352222831f098d0f50785f5aa453744b2e07c
2026-01-05T05:18:29.067673Z
false
saxap/clean-wp-template
https://github.com/saxap/clean-wp-template/blob/30d352222831f098d0f50785f5aa453744b2e07c/your-clean-template-3/404.php
your-clean-template-3/404.php
<?php /** * Страница 404 ошибки (404.php) * @package WordPress * @subpackage your-clean-template-3 */ get_header(); // Подключаем header.php ?> <section> <div class="container"> <div class="row"> <div class="<?php content_class_by_sidebar(); // функция подставит класс в зависимости от того есть ли сайдбар, лежит в functions.php ?>"> <h1>Ой, это 404!</h1> <p>Блаблабла 404 Блаблабла</p> </div> <?php get_sidebar(); // подключаем sidebar.php ?> </div> </div> </section> <?php get_footer(); // подключаем footer.php ?>
php
MIT
30d352222831f098d0f50785f5aa453744b2e07c
2026-01-05T05:18:29.067673Z
false
saxap/clean-wp-template
https://github.com/saxap/clean-wp-template/blob/30d352222831f098d0f50785f5aa453744b2e07c/your-clean-template-3/header.php
your-clean-template-3/header.php
<?php /** * Шаблон шапки (header.php) * @package WordPress * @subpackage your-clean-template-3 */ ?> <!DOCTYPE html> <html <?php language_attributes(); // вывод атрибутов языка ?>> <head> <meta charset="<?php bloginfo( 'charset' ); // кодировка ?>"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <?php /* RSS и всякое */ ?> <link rel="alternate" type="application/rdf+xml" title="RDF mapping" href="<?php bloginfo('rdf_url'); ?>"> <link rel="alternate" type="application/rss+xml" title="RSS" href="<?php bloginfo('rss_url'); ?>"> <link rel="alternate" type="application/rss+xml" title="Comments RSS" href="<?php bloginfo('comments_rss2_url'); ?>"> <link rel="pingback" href="<?php bloginfo( 'pingback_url' ); ?>" /> <?php /* Все скрипты и стили теперь подключаются в functions.php */ ?> <!--[if lt IE 9]> <script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script> <![endif]--> <?php wp_head(); // необходимо для работы плагинов и функционала ?> </head> <body <?php body_class(); // все классы для body ?>> <header> <div class="container"> <div class="row"> <div class="col-md-12"> <nav class="navbar navbar-default"> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#topnav" aria-expanded="false"> <span class="sr-only">Меню</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> </div> <div class="collapse navbar-collapse" id="topnav"> <?php $args = array( // опции для вывода верхнего меню, чтобы они работали, меню должно быть создано в админке 'theme_location' => 'top', // идентификатор меню, определен в register_nav_menus() в functions.php 'container'=> false, // обертка списка, тут не нужна 'menu_id' => 'top-nav-ul', // id для ul 'items_wrap' => '<ul id="%1$s" class="nav navbar-nav %2$s">%3$s</ul>', 'menu_class' => 'top-menu', // класс для ul, первые 2 обязательны 'walker' => new bootstrap_menu(true) // верхнее меню выводится по разметке бутсрапа, см класс в functions.php, если по наведению субменю не раскрывать то передайте false ); wp_nav_menu($args); // выводим верхнее меню ?> </div> </nav> </div> </div> </div> </header>
php
MIT
30d352222831f098d0f50785f5aa453744b2e07c
2026-01-05T05:18:29.067673Z
false
saxap/clean-wp-template
https://github.com/saxap/clean-wp-template/blob/30d352222831f098d0f50785f5aa453744b2e07c/your-clean-template-3/single.php
your-clean-template-3/single.php
<?php /** * Шаблон отдельной записи (single.php) * @package WordPress * @subpackage your-clean-template-3 */ get_header(); // подключаем header.php ?> <section> <div class="container"> <div class="row"> <div class="<?php content_class_by_sidebar(); // функция подставит класс в зависимости от того есть ли сайдбар, лежит в functions.php ?>"> <?php if ( have_posts() ) while ( have_posts() ) : the_post(); // старт цикла ?> <article id="post-<?php the_ID(); ?>" <?php post_class(); ?>> <?php // контэйнер с классами и id ?> <h1><?php the_title(); // заголовок поста ?></h1> <div class="meta"> <p>Опубликовано: <?php the_time(get_option('date_format')." в ".get_option('time_format')); ?></p> <?php // дата и время создания ?> <p>Автор: <?php the_author_posts_link(); ?></p> <p>Категории: <?php the_category(',') ?></p> <?php // ссылки на категории в которых опубликован пост, через зпт ?> <?php the_tags('<p>Тэги: ', ',', '</p>'); // ссылки на тэги поста ?> </div> <?php the_content(); // контент ?> </article> <?php endwhile; // конец цикла ?> <?php previous_post_link('%link', '<- Предыдущий пост: %title', TRUE); // ссылка на предыдущий пост ?> <?php next_post_link('%link', 'Следующий пост: %title ->', TRUE); // ссылка на следующий пост ?> <?php if (comments_open() || get_comments_number()) comments_template('', true); // если комментирование открыто - мы покажем список комментариев и форму, если закрыто, но кол-во комментов > 0 - покажем только список комментариев ?> </div> <?php get_sidebar(); // подключаем sidebar.php ?> </div> </div> </section> <?php get_footer(); // подключаем footer.php ?>
php
MIT
30d352222831f098d0f50785f5aa453744b2e07c
2026-01-05T05:18:29.067673Z
false
saxap/clean-wp-template
https://github.com/saxap/clean-wp-template/blob/30d352222831f098d0f50785f5aa453744b2e07c/your-clean-template-3/searchform.php
your-clean-template-3/searchform.php
<?php /** * Шаблон формы поиска (searchform.php) * @package WordPress * @subpackage your-clean-template-3 */ ?> <form role="search" method="get" class="search-form form-inline" action="<?php echo home_url( '/' ); ?>"> <div class="form-group"> <label class="sr-only" for="search-field">Поиск</label> <input type="search" class="form-control input-sm" id="search-field" placeholder="Строка для поиска" value="<?php echo get_search_query() ?>" name="s"> </div> <button type="submit" class="btn btn-default btn-sm">Искать</button> </form>
php
MIT
30d352222831f098d0f50785f5aa453744b2e07c
2026-01-05T05:18:29.067673Z
false
saxap/clean-wp-template
https://github.com/saxap/clean-wp-template/blob/30d352222831f098d0f50785f5aa453744b2e07c/your-clean-template-3/sidebar.php
your-clean-template-3/sidebar.php
<?php /** * Шаблон сайдбара (sidebar.php) * @package WordPress * @subpackage your-clean-template-3 */ ?> <?php if (is_active_sidebar( 'sidebar' )) { // если в сайдбаре есть что выводить ?> <aside class="col-sm-3"> <?php dynamic_sidebar('sidebar'); // выводим сайдбар, имя определено в functions.php ?> </aside> <?php } ?>
php
MIT
30d352222831f098d0f50785f5aa453744b2e07c
2026-01-05T05:18:29.067673Z
false
zendframework/zend-http
https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/src/Client.php
src/Client.php
<?php /** * @see https://github.com/zendframework/zend-http for the canonical source repository * @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com) * @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License */ namespace Zend\Http; use ArrayIterator; use Traversable; use Zend\Http\Client\Adapter\Curl; use Zend\Http\Client\Adapter\Socket; use Zend\Http\Header\SetCookie; use Zend\Stdlib; use Zend\Stdlib\ArrayUtils; use Zend\Stdlib\ErrorHandler; use Zend\Uri\Http; /** * Http client */ class Client implements Stdlib\DispatchableInterface { /** * @const string Supported HTTP Authentication methods */ const AUTH_BASIC = 'basic'; const AUTH_DIGEST = 'digest'; /** * @const string POST data encoding methods */ const ENC_URLENCODED = 'application/x-www-form-urlencoded'; const ENC_FORMDATA = 'multipart/form-data'; /** * @const string DIGEST Authentication */ const DIGEST_REALM = 'realm'; const DIGEST_QOP = 'qop'; const DIGEST_NONCE = 'nonce'; const DIGEST_OPAQUE = 'opaque'; const DIGEST_NC = 'nc'; const DIGEST_CNONCE = 'cnonce'; /** * @var Response */ protected $response; /** * @var Request */ protected $request; /** * @var Client\Adapter\AdapterInterface */ protected $adapter; /** * @var array */ protected $auth = []; /** * @var string */ protected $streamName; /** * @var resource|null */ protected $streamHandle = null; /** * @var array of Header\SetCookie */ protected $cookies = []; /** * @var string */ protected $encType = ''; /** * @var Request */ protected $lastRawRequest; /** * @var Response */ protected $lastRawResponse; /** * @var int */ protected $redirectCounter = 0; /** * Configuration array, set using the constructor or using ::setOptions() * * @var array */ protected $config = [ 'maxredirects' => 5, 'strictredirects' => false, 'useragent' => Client::class, 'timeout' => 10, 'connecttimeout' => null, 'adapter' => Socket::class, 'httpversion' => Request::VERSION_11, 'storeresponse' => true, 'keepalive' => false, 'outputstream' => false, 'encodecookies' => true, 'argseparator' => null, 'rfc3986strict' => false, 'sslcafile' => null, 'sslcapath' => null, ]; /** * Fileinfo magic database resource * * This variable is populated the first time _detectFileMimeType is called * and is then reused on every call to this method * * @var resource */ protected static $fileInfoDb; /** * Constructor * * @param string $uri * @param array|Traversable $options */ public function __construct($uri = null, $options = null) { if ($uri !== null) { $this->setUri($uri); } if ($options !== null) { $this->setOptions($options); } } /** * Set configuration parameters for this HTTP client * * @param array|Traversable $options * @return $this * @throws Client\Exception\InvalidArgumentException */ public function setOptions($options = []) { if ($options instanceof Traversable) { $options = ArrayUtils::iteratorToArray($options); } if (! is_array($options)) { throw new Client\Exception\InvalidArgumentException('Config parameter is not valid'); } /** Config Key Normalization */ foreach ($options as $k => $v) { $this->config[str_replace(['-', '_', ' ', '.'], '', strtolower($k))] = $v; // replace w/ normalized } // Pass configuration options to the adapter if it exists if ($this->adapter instanceof Client\Adapter\AdapterInterface) { $this->adapter->setOptions($options); } return $this; } /** * Load the connection adapter * * While this method is not called more than one for a client, it is * separated from ->request() to preserve logic and readability * * @param Client\Adapter\AdapterInterface|string $adapter * @return $this * @throws Client\Exception\InvalidArgumentException */ public function setAdapter($adapter) { if (is_string($adapter)) { if (! class_exists($adapter)) { throw new Client\Exception\InvalidArgumentException( 'Unable to locate adapter class "' . $adapter . '"' ); } $adapter = new $adapter; } if (! $adapter instanceof Client\Adapter\AdapterInterface) { throw new Client\Exception\InvalidArgumentException('Passed adapter is not a HTTP connection adapter'); } $this->adapter = $adapter; $config = $this->config; unset($config['adapter']); $this->adapter->setOptions($config); return $this; } /** * Load the connection adapter * * @return Client\Adapter\AdapterInterface */ public function getAdapter() { if (! $this->adapter) { $this->setAdapter($this->config['adapter']); } return $this->adapter; } /** * Set request * * @param Request $request * @return $this */ public function setRequest(Request $request) { $this->request = $request; return $this; } /** * Get Request * * @return Request */ public function getRequest() { if (empty($this->request)) { $this->request = new Request(); $this->request->setAllowCustomMethods(false); } return $this->request; } /** * Set response * * @param Response $response * @return $this */ public function setResponse(Response $response) { $this->response = $response; return $this; } /** * Get Response * * @return Response */ public function getResponse() { if (empty($this->response)) { $this->response = new Response(); } return $this->response; } /** * Get the last request (as a string) * * @return string */ public function getLastRawRequest() { return $this->lastRawRequest; } /** * Get the last response (as a string) * * @return string */ public function getLastRawResponse() { return $this->lastRawResponse; } /** * Get the redirections count * * @return int */ public function getRedirectionsCount() { return $this->redirectCounter; } /** * Set Uri (to the request) * * @param string|Http $uri * @return $this */ public function setUri($uri) { if (! empty($uri)) { // remember host of last request $lastHost = $this->getRequest()->getUri()->getHost(); $this->getRequest()->setUri($uri); // if host changed, the HTTP authentication should be cleared for security // reasons, see #4215 for a discussion - currently authentication is also // cleared for peer subdomains due to technical limits $nextHost = $this->getRequest()->getUri()->getHost(); if (! preg_match('/' . preg_quote($lastHost, '/') . '$/i', $nextHost)) { $this->clearAuth(); } $uri = $this->getUri(); $user = $uri->getUser(); $password = $uri->getPassword(); // Set auth if username and password has been specified in the uri if ($user && $password) { $this->setAuth($user, $password); } // We have no ports, set the defaults if (! $uri->getPort() && $uri->isAbsolute()) { $uri->setPort($uri->getScheme() === 'https' ? 443 : 80); } } return $this; } /** * Get uri (from the request) * * @return Http */ public function getUri() { return $this->getRequest()->getUri(); } /** * Set the HTTP method (to the request) * * @param string $method * @return $this */ public function setMethod($method) { $method = $this->getRequest()->setMethod($method)->getMethod(); if (empty($this->encType) && in_array( $method, [ Request::METHOD_POST, Request::METHOD_PUT, Request::METHOD_DELETE, Request::METHOD_PATCH, Request::METHOD_OPTIONS, ], true ) ) { $this->setEncType(self::ENC_URLENCODED); } return $this; } /** * Get the HTTP method * * @return string */ public function getMethod() { return $this->getRequest()->getMethod(); } /** * Set the query string argument separator * * @param string $argSeparator * @return $this */ public function setArgSeparator($argSeparator) { $this->setOptions(['argseparator' => $argSeparator]); return $this; } /** * Get the query string argument separator * * @return string */ public function getArgSeparator() { $argSeparator = $this->config['argseparator']; if (empty($argSeparator)) { $argSeparator = ini_get('arg_separator.output'); $this->setArgSeparator($argSeparator); } return $argSeparator; } /** * Set the encoding type and the boundary (if any) * * @param string $encType * @param string $boundary * @return $this */ public function setEncType($encType, $boundary = null) { if (null === $encType || empty($encType)) { $this->encType = null; return $this; } if (! empty($boundary)) { $encType .= sprintf('; boundary=%s', $boundary); } $this->encType = $encType; return $this; } /** * Get the encoding type * * @return string */ public function getEncType() { return $this->encType; } /** * Set raw body (for advanced use cases) * * @param string $body * @return $this */ public function setRawBody($body) { $this->getRequest()->setContent($body); return $this; } /** * Set the POST parameters * * @param array $post * @return $this */ public function setParameterPost(array $post) { $this->getRequest()->getPost()->fromArray($post); return $this; } /** * Set the GET parameters * * @param array $query * @return $this */ public function setParameterGet(array $query) { $this->getRequest()->getQuery()->fromArray($query); return $this; } /** * Reset all the HTTP parameters (request, response, etc) * * @param bool $clearCookies Also clear all valid cookies? (defaults to false) * @param bool $clearAuth Also clear http authentication? (defaults to true) * @return $this */ public function resetParameters($clearCookies = false /*, $clearAuth = true */) { $clearAuth = true; if (func_num_args() > 1) { $clearAuth = func_get_arg(1); } $uri = $this->getUri(); $this->streamName = null; $this->encType = null; $this->request = null; $this->response = null; $this->lastRawRequest = null; $this->lastRawResponse = null; $this->setUri($uri); if ($clearCookies) { $this->clearCookies(); } if ($clearAuth) { $this->clearAuth(); } return $this; } /** * Return the current cookies * * @return array */ public function getCookies() { return $this->cookies; } /** * Get the cookie Id (name+domain+path) * * @param Header\SetCookie|Header\Cookie $cookie * @return string|bool */ protected function getCookieId($cookie) { if (($cookie instanceof Header\SetCookie) || ($cookie instanceof Header\Cookie)) { return $cookie->getName() . $cookie->getDomain() . $cookie->getPath(); } return false; } /** * Add a cookie * * @param array|ArrayIterator|Header\SetCookie|string $cookie * @param string $value * @param string $expire * @param string $path * @param string $domain * @param bool $secure * @param bool $httponly * @param string $maxAge * @param string $version * @throws Exception\InvalidArgumentException * @return $this */ public function addCookie( $cookie, $value = null, $expire = null, $path = null, $domain = null, $secure = false, $httponly = true, $maxAge = null, $version = null ) { if (is_array($cookie) || $cookie instanceof ArrayIterator) { foreach ($cookie as $setCookie) { if ($setCookie instanceof Header\SetCookie) { $this->cookies[$this->getCookieId($setCookie)] = $setCookie; } else { throw new Exception\InvalidArgumentException('The cookie parameter is not a valid Set-Cookie type'); } } } elseif (is_string($cookie) && $value !== null) { $setCookie = new Header\SetCookie( $cookie, $value, $expire, $path, $domain, $secure, $httponly, $maxAge, $version ); $this->cookies[$this->getCookieId($setCookie)] = $setCookie; } elseif ($cookie instanceof Header\SetCookie) { $this->cookies[$this->getCookieId($cookie)] = $cookie; } else { throw new Exception\InvalidArgumentException('Invalid parameter type passed as Cookie'); } return $this; } /** * Set an array of cookies * * @param array|SetCookie[] $cookies Cookies as name=>value pairs or instances of SetCookie. * @throws Exception\InvalidArgumentException * @return $this */ public function setCookies($cookies) { if (is_array($cookies)) { $this->clearCookies(); foreach ($cookies as $name => $value) { if ($value instanceof SetCookie) { $this->addCookie($value); } else { $this->addCookie($name, $value); } } } else { throw new Exception\InvalidArgumentException('Invalid cookies passed as parameter, it must be an array'); } return $this; } /** * Clear all the cookies */ public function clearCookies() { $this->cookies = []; } /** * Set the headers (for the request) * * @param Headers|array $headers * @throws Exception\InvalidArgumentException * @return $this */ public function setHeaders($headers) { if (is_array($headers)) { $newHeaders = new Headers(); $newHeaders->addHeaders($headers); $this->getRequest()->setHeaders($newHeaders); } elseif ($headers instanceof Headers) { $this->getRequest()->setHeaders($headers); } else { throw new Exception\InvalidArgumentException('Invalid parameter headers passed'); } return $this; } /** * Check if exists the header type specified * * @param string $name * @return bool */ public function hasHeader($name) { $headers = $this->getRequest()->getHeaders(); if ($headers instanceof Headers) { return $headers->has($name); } return false; } /** * Get the header value of the request * * @param string $name * @return string|bool */ public function getHeader($name) { $headers = $this->getRequest()->getHeaders(); if ($headers instanceof Headers) { if ($headers->get($name)) { return $headers->get($name)->getFieldValue(); } } return false; } /** * Set streaming for received data * * @param string|bool $streamfile Stream file, true for temp file, false/null for no streaming * @return $this */ public function setStream($streamfile = true) { $this->setOptions(['outputstream' => $streamfile]); return $this; } /** * Get status of streaming for received data * @return bool|string */ public function getStream() { if (null !== $this->streamName) { return $this->streamName; } return $this->config['outputstream']; } /** * Create temporary stream * * @return resource * @throws Exception\RuntimeException */ protected function openTempStream() { $this->streamName = $this->config['outputstream']; if (! is_string($this->streamName)) { // If name is not given, create temp name $this->streamName = tempnam( isset($this->config['streamtmpdir']) ? $this->config['streamtmpdir'] : sys_get_temp_dir(), Client::class ); } ErrorHandler::start(); $fp = fopen($this->streamName, 'w+b'); $error = ErrorHandler::stop(); if (false === $fp) { if ($this->adapter instanceof Client\Adapter\AdapterInterface) { $this->adapter->close(); } throw new Exception\RuntimeException(sprintf('Could not open temp file %s', $this->streamName), 0, $error); } return $fp; } /** * Create a HTTP authentication "Authorization:" header according to the * specified user, password and authentication method. * * @param string $user * @param string $password * @param string $type * @throws Exception\InvalidArgumentException * @return $this */ public function setAuth($user, $password, $type = self::AUTH_BASIC) { if (! defined('static::AUTH_' . strtoupper($type))) { throw new Exception\InvalidArgumentException(sprintf( 'Invalid or not supported authentication type: \'%s\'', $type )); } if (empty($user)) { throw new Exception\InvalidArgumentException('The username cannot be empty'); } $this->auth = [ 'user' => $user, 'password' => $password, 'type' => $type, ]; return $this; } /** * Clear http authentication */ public function clearAuth() { $this->auth = []; } /** * Calculate the response value according to the HTTP authentication type * * @see http://www.faqs.org/rfcs/rfc2617.html * @param string $user * @param string $password * @param string $type * @param array $digest * @param null|string $entityBody * @throws Exception\InvalidArgumentException * @return string|bool */ protected function calcAuthDigest($user, $password, $type = self::AUTH_BASIC, $digest = [], $entityBody = null) { if (! defined('self::AUTH_' . strtoupper($type))) { throw new Exception\InvalidArgumentException(sprintf( 'Invalid or not supported authentication type: \'%s\'', $type )); } $response = false; switch (strtolower($type)) { case self::AUTH_BASIC: // In basic authentication, the user name cannot contain ":" if (strpos($user, ':') !== false) { throw new Exception\InvalidArgumentException( 'The user name cannot contain \':\' in Basic HTTP authentication' ); } $response = base64_encode($user . ':' . $password); break; case self::AUTH_DIGEST: if (empty($digest)) { throw new Exception\InvalidArgumentException('The digest cannot be empty'); } foreach ($digest as $key => $value) { if (! defined('self::DIGEST_' . strtoupper($key))) { throw new Exception\InvalidArgumentException(sprintf( 'Invalid or not supported digest authentication parameter: \'%s\'', $key )); } } $ha1 = md5($user . ':' . $digest['realm'] . ':' . $password); if (empty($digest['qop']) || strtolower($digest['qop']) == 'auth') { $ha2 = md5($this->getMethod() . ':' . $this->getUri()->getPath()); } elseif (strtolower($digest['qop']) == 'auth-int') { if (empty($entityBody)) { throw new Exception\InvalidArgumentException( 'I cannot use the auth-int digest authentication without the entity body' ); } $ha2 = md5($this->getMethod() . ':' . $this->getUri()->getPath() . ':' . md5($entityBody)); } if (empty($digest['qop'])) { $response = md5($ha1 . ':' . $digest['nonce'] . ':' . $ha2); } else { $response = md5($ha1 . ':' . $digest['nonce'] . ':' . $digest['nc'] . ':' . $digest['cnonce'] . ':' . $digest['qoc'] . ':' . $ha2); } break; } return $response; } /** * Dispatch * * @param Stdlib\RequestInterface $request * @param Stdlib\ResponseInterface $response * @return Stdlib\ResponseInterface */ public function dispatch(Stdlib\RequestInterface $request, Stdlib\ResponseInterface $response = null) { return $this->send($request); } /** * Send HTTP request * * @param Request|null $request * @return Response * @throws Exception\RuntimeException * @throws Client\Exception\RuntimeException */ public function send(Request $request = null) { if ($request !== null) { $this->setRequest($request); } $this->redirectCounter = 0; $adapter = $this->getAdapter(); // Send the first request. If redirected, continue. do { // uri $uri = $this->getUri(); // query $query = $this->getRequest()->getQuery(); if (! empty($query)) { $queryArray = $query->toArray(); if (! empty($queryArray)) { $newUri = $uri->toString(); $queryString = http_build_query($queryArray, null, $this->getArgSeparator()); if ($this->config['rfc3986strict']) { $queryString = str_replace('+', '%20', $queryString); } if (strpos($newUri, '?') !== false) { $newUri .= $this->getArgSeparator() . $queryString; } else { $newUri .= '?' . $queryString; } $uri = new Http($newUri); } } // If we have no ports, set the defaults if (! $uri->getPort() && $uri->isAbsolute()) { $uri->setPort($uri->getScheme() === 'https' ? 443 : 80); } // method $method = $this->getRequest()->getMethod(); // this is so the correct Encoding Type is set $this->setMethod($method); // body $body = $this->prepareBody(); // headers $headers = $this->prepareHeaders($body, $uri); $secure = $uri->getScheme() == 'https'; // cookies $cookie = $this->prepareCookies($uri->getHost(), $uri->getPath(), $secure); if ($cookie->getFieldValue()) { $headers['Cookie'] = $cookie->getFieldValue(); } // check that adapter supports streaming before using it if (is_resource($body) && ! ($adapter instanceof Client\Adapter\StreamInterface)) { throw new Client\Exception\RuntimeException('Adapter does not support streaming'); } $this->streamHandle = null; // calling protected method to allow extending classes // to wrap the interaction with the adapter $response = $this->doRequest($uri, $method, $secure, $headers, $body); $stream = $this->streamHandle; $this->streamHandle = null; if (! $response) { if ($stream !== null) { fclose($stream); } throw new Exception\RuntimeException('Unable to read response, or response is empty'); } if ($this->config['storeresponse']) { $this->lastRawResponse = $response; } else { $this->lastRawResponse = null; } if ($this->config['outputstream']) { if ($stream === null) { $stream = $this->getStream(); if (! is_resource($stream) && is_string($stream)) { $stream = fopen($stream, 'r'); } } $streamMetaData = stream_get_meta_data($stream); if ($streamMetaData['seekable']) { rewind($stream); } // cleanup the adapter $adapter->setOutputStream(null); $response = Response\Stream::fromStream($response, $stream); $response->setStreamName($this->streamName); if (! is_string($this->config['outputstream'])) { // we used temp name, will need to clean up $response->setCleanup(true); } } else { $response = $this->getResponse()->fromString($response); } // Get the cookies from response (if any) $setCookies = $response->getCookie(); if (! empty($setCookies)) { $this->addCookie($setCookies); } // If we got redirected, look for the Location header if ($response->isRedirect() && ($response->getHeaders()->has('Location'))) { // Avoid problems with buggy servers that add whitespace at the // end of some headers $location = trim($response->getHeaders()->get('Location')->getFieldValue()); // Check whether we send the exact same request again, or drop the parameters // and send a GET request if ($response->getStatusCode() == 303 || ((! $this->config['strictredirects']) && ($response->getStatusCode() == 302 || $response->getStatusCode() == 301)) ) { $this->resetParameters(false, false); $this->setMethod(Request::METHOD_GET); } // If we got a well formed absolute URI if (($scheme = substr($location, 0, 6)) && ($scheme == 'http:/' || $scheme == 'https:') ) { // setURI() clears parameters if host changed, see #4215 $this->setUri($location); } else { // Split into path and query and set the query if (strpos($location, '?') !== false) { list($location, $query) = explode('?', $location, 2); } else { $query = ''; } $this->getUri()->setQuery($query); // Else, if we got just an absolute path, set it if (strpos($location, '/') === 0) { $this->getUri()->setPath($location); // Else, assume we have a relative path } else { // Get the current path directory, removing any trailing slashes $path = $this->getUri()->getPath(); $path = rtrim(substr($path, 0, strrpos($path, '/')), '/'); $this->getUri()->setPath($path . '/' . $location); } } ++$this->redirectCounter; } else { // If we didn't get any location, stop redirecting break; } } while ($this->redirectCounter <= $this->config['maxredirects']); $this->response = $response; return $response; } /** * Fully reset the HTTP client (auth, cookies, request, response, etc.) * * @return $this */ public function reset() { $this->resetParameters(); $this->clearAuth(); $this->clearCookies(); return $this; } /** * Set a file to upload (using a POST request) * * Can be used in two ways: * * 1. $data is null (default): $filename is treated as the name if a local file which * will be read and sent. Will try to guess the content type using mime_content_type(). * 2. $data is set - $filename is sent as the file name, but $data is sent as the file * contents and no file is read from the file system. In this case, you need to * manually set the Content-Type ($ctype) or it will default to * application/octet-stream. * * @param string $filename Name of file to upload, or name to save as * @param string $formname Name of form element to send as * @param string $data Data to send (if null, $filename is read and sent) * @param string $ctype Content type to use (if $data is set and $ctype is * null, will be application/octet-stream) * @return $this * @throws Exception\RuntimeException */ public function setFileUpload($filename, $formname, $data = null, $ctype = null) { if ($data === null) { ErrorHandler::start(); $data = file_get_contents($filename); $error = ErrorHandler::stop(); if ($data === false) { throw new Exception\RuntimeException(sprintf( 'Unable to read file \'%s\' for upload', $filename ), 0, $error); } if (! $ctype) { $ctype = $this->detectFileMimeType($filename); } } $this->getRequest()->getFiles()->set($filename, [ 'formname' => $formname, 'filename' => basename($filename), 'ctype' => $ctype, 'data' => $data, ]); return $this; } /** * Remove a file to upload * * @param string $filename * @return bool */ public function removeFileUpload($filename) { $file = $this->getRequest()->getFiles()->get($filename); if (! empty($file)) { $this->getRequest()->getFiles()->set($filename, null); return true; } return false; } /** * Prepare Cookies * * @param string $domain * @param string $path * @param bool $secure * @return Header\Cookie|bool */
php
BSD-3-Clause
ac4ffd09d509b2c5c0285178c4f7de740f05c3d9
2026-01-05T05:18:13.309357Z
true
zendframework/zend-http
https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/src/Request.php
src/Request.php
<?php /** * @see https://github.com/zendframework/zend-http for the canonical source repository * @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com) * @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License */ namespace Zend\Http; use Zend\Stdlib\Parameters; use Zend\Stdlib\ParametersInterface; use Zend\Stdlib\RequestInterface; use Zend\Uri\Exception as UriException; use Zend\Uri\Http as HttpUri; /** * HTTP Request * * @link http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5 */ class Request extends AbstractMessage implements RequestInterface { /**#@+ * @const string METHOD constant names */ const METHOD_OPTIONS = 'OPTIONS'; const METHOD_GET = 'GET'; const METHOD_HEAD = 'HEAD'; const METHOD_POST = 'POST'; const METHOD_PUT = 'PUT'; const METHOD_DELETE = 'DELETE'; const METHOD_TRACE = 'TRACE'; const METHOD_CONNECT = 'CONNECT'; const METHOD_PATCH = 'PATCH'; const METHOD_PROPFIND = 'PROPFIND'; /**#@-*/ /** * @var string */ protected $method = self::METHOD_GET; /** * @var bool */ protected $allowCustomMethods = true; /** * @var string|HttpUri */ protected $uri; /** * @var ParametersInterface */ protected $queryParams; /** * @var ParametersInterface */ protected $postParams; /** * @var ParametersInterface */ protected $fileParams; /** * A factory that produces a Request object from a well-formed Http Request string * * @param string $string * @param bool $allowCustomMethods * @throws Exception\InvalidArgumentException * @return static */ public static function fromString($string, $allowCustomMethods = true) { $request = new static(); $request->setAllowCustomMethods($allowCustomMethods); $lines = explode("\r\n", $string); // first line must be Method/Uri/Version string $matches = null; $methods = $allowCustomMethods ? '[\w-]+' : implode( '|', [ self::METHOD_OPTIONS, self::METHOD_GET, self::METHOD_HEAD, self::METHOD_POST, self::METHOD_PUT, self::METHOD_DELETE, self::METHOD_TRACE, self::METHOD_CONNECT, self::METHOD_PATCH, ] ); $regex = '#^(?P<method>' . $methods . ')\s(?P<uri>[^ ]*)(?:\sHTTP\/(?P<version>\d+\.\d+)){0,1}#'; $firstLine = array_shift($lines); if (! preg_match($regex, $firstLine, $matches)) { throw new Exception\InvalidArgumentException( 'A valid request line was not found in the provided string' ); } $request->setMethod($matches['method']); $request->setUri($matches['uri']); $parsedUri = parse_url($matches['uri']); if (array_key_exists('query', $parsedUri)) { $parsedQuery = []; parse_str($parsedUri['query'], $parsedQuery); $request->setQuery(new Parameters($parsedQuery)); } if (isset($matches['version'])) { $request->setVersion($matches['version']); } if (empty($lines)) { return $request; } $isHeader = true; $headers = $rawBody = []; while ($lines) { $nextLine = array_shift($lines); if ($nextLine == '') { $isHeader = false; continue; } if ($isHeader) { if (preg_match("/[\r\n]/", $nextLine)) { throw new Exception\RuntimeException('CRLF injection detected'); } $headers[] = $nextLine; continue; } if (empty($rawBody) && preg_match('/^[a-z0-9!#$%&\'*+.^_`|~-]+:$/i', $nextLine) ) { throw new Exception\RuntimeException('CRLF injection detected'); } $rawBody[] = $nextLine; } if ($headers) { $request->headers = implode("\r\n", $headers); } if ($rawBody) { $request->setContent(implode("\r\n", $rawBody)); } return $request; } /** * Set the method for this request * * @param string $method * @return $this * @throws Exception\InvalidArgumentException */ public function setMethod($method) { $method = strtoupper($method); if (! defined('static::METHOD_' . $method) && ! $this->getAllowCustomMethods()) { throw new Exception\InvalidArgumentException('Invalid HTTP method passed'); } $this->method = $method; return $this; } /** * Return the method for this request * * @return string */ public function getMethod() { return $this->method; } /** * Set the URI/URL for this request, this can be a string or an instance of Zend\Uri\Http * * @throws Exception\InvalidArgumentException * @param string|HttpUri $uri * @return $this */ public function setUri($uri) { if (is_string($uri)) { try { $uri = new HttpUri($uri); } catch (UriException\InvalidUriPartException $e) { throw new Exception\InvalidArgumentException( sprintf('Invalid URI passed as string (%s)', (string) $uri), $e->getCode(), $e ); } } elseif (! ($uri instanceof HttpUri)) { throw new Exception\InvalidArgumentException( 'URI must be an instance of Zend\Uri\Http or a string' ); } $this->uri = $uri; return $this; } /** * Return the URI for this request object * * @return HttpUri */ public function getUri() { if ($this->uri === null || is_string($this->uri)) { $this->uri = new HttpUri($this->uri); } return $this->uri; } /** * Return the URI for this request object as a string * * @return string */ public function getUriString() { if ($this->uri instanceof HttpUri) { return $this->uri->toString(); } return $this->uri; } /** * Provide an alternate Parameter Container implementation for query parameters in this object, * (this is NOT the primary API for value setting, for that see getQuery()) * * @param ParametersInterface $query * @return $this */ public function setQuery(ParametersInterface $query) { $this->queryParams = $query; return $this; } /** * Return the parameter container responsible for query parameters or a single query parameter * * @param string|null $name Parameter name to retrieve, or null to get the whole container. * @param mixed|null $default Default value to use when the parameter is missing. * @return ParametersInterface|mixed */ public function getQuery($name = null, $default = null) { if ($this->queryParams === null) { $this->queryParams = new Parameters(); } if ($name === null) { return $this->queryParams; } return $this->queryParams->get($name, $default); } /** * Provide an alternate Parameter Container implementation for post parameters in this object, * (this is NOT the primary API for value setting, for that see getPost()) * * @param ParametersInterface $post * @return $this */ public function setPost(ParametersInterface $post) { $this->postParams = $post; return $this; } /** * Return the parameter container responsible for post parameters or a single post parameter. * * @param string|null $name Parameter name to retrieve, or null to get the whole container. * @param mixed|null $default Default value to use when the parameter is missing. * @return ParametersInterface|mixed */ public function getPost($name = null, $default = null) { if ($this->postParams === null) { $this->postParams = new Parameters(); } if ($name === null) { return $this->postParams; } return $this->postParams->get($name, $default); } /** * Return the Cookie header, this is the same as calling $request->getHeaders()->get('Cookie'); * * @convenience $request->getHeaders()->get('Cookie'); * @return Header\Cookie|bool */ public function getCookie() { return $this->getHeaders()->get('Cookie'); } /** * Provide an alternate Parameter Container implementation for file parameters in this object, * (this is NOT the primary API for value setting, for that see getFiles()) * * @param ParametersInterface $files * @return $this */ public function setFiles(ParametersInterface $files) { $this->fileParams = $files; return $this; } /** * Return the parameter container responsible for file parameters or a single file. * * @param string|null $name Parameter name to retrieve, or null to get the whole container. * @param mixed|null $default Default value to use when the parameter is missing. * @return ParametersInterface|mixed */ public function getFiles($name = null, $default = null) { if ($this->fileParams === null) { $this->fileParams = new Parameters(); } if ($name === null) { return $this->fileParams; } return $this->fileParams->get($name, $default); } /** * Return the header container responsible for headers or all headers of a certain name/type * * @see \Zend\Http\Headers::get() * @param string|null $name Header name to retrieve, or null to get the whole container. * @param mixed|null $default Default value to use when the requested header is missing. * @return \Zend\Http\Headers|bool|\Zend\Http\Header\HeaderInterface|\ArrayIterator */ public function getHeaders($name = null, $default = false) { if ($this->headers === null || is_string($this->headers)) { // this is only here for fromString lazy loading $this->headers = (is_string($this->headers)) ? Headers::fromString($this->headers) : new Headers(); } if ($name === null) { return $this->headers; } if ($this->headers->has($name)) { return $this->headers->get($name); } return $default; } /** * Get all headers of a certain name/type. * * @see Request::getHeaders() * @param string|null $name Header name to retrieve, or null to get the whole container. * @param mixed|null $default Default value to use when the requested header is missing. * @return \Zend\Http\Headers|bool|\Zend\Http\Header\HeaderInterface|\ArrayIterator */ public function getHeader($name, $default = false) { return $this->getHeaders($name, $default); } /** * Is this an OPTIONS method request? * * @return bool */ public function isOptions() { return ($this->method === self::METHOD_OPTIONS); } /** * Is this a PROPFIND method request? * * @return bool */ public function isPropFind() { return ($this->method === self::METHOD_PROPFIND); } /** * Is this a GET method request? * * @return bool */ public function isGet() { return ($this->method === self::METHOD_GET); } /** * Is this a HEAD method request? * * @return bool */ public function isHead() { return ($this->method === self::METHOD_HEAD); } /** * Is this a POST method request? * * @return bool */ public function isPost() { return ($this->method === self::METHOD_POST); } /** * Is this a PUT method request? * * @return bool */ public function isPut() { return ($this->method === self::METHOD_PUT); } /** * Is this a DELETE method request? * * @return bool */ public function isDelete() { return ($this->method === self::METHOD_DELETE); } /** * Is this a TRACE method request? * * @return bool */ public function isTrace() { return ($this->method === self::METHOD_TRACE); } /** * Is this a CONNECT method request? * * @return bool */ public function isConnect() { return ($this->method === self::METHOD_CONNECT); } /** * Is this a PATCH method request? * * @return bool */ public function isPatch() { return ($this->method === self::METHOD_PATCH); } /** * Is the request a Javascript XMLHttpRequest? * * Should work with Prototype/Script.aculo.us, possibly others. * * @return bool */ public function isXmlHttpRequest() { $header = $this->getHeaders()->get('X_REQUESTED_WITH'); return false !== $header && $header->getFieldValue() == 'XMLHttpRequest'; } /** * Is this a Flash request? * * @return bool */ public function isFlashRequest() { $header = $this->getHeaders()->get('USER_AGENT'); return false !== $header && stristr($header->getFieldValue(), ' flash'); } /** * Return the formatted request line (first line) for this http request * * @return string */ public function renderRequestLine() { return $this->method . ' ' . (string) $this->uri . ' HTTP/' . $this->version; } /** * @return string */ public function toString() { $str = $this->renderRequestLine() . "\r\n"; $str .= $this->getHeaders()->toString(); $str .= "\r\n"; $str .= $this->getContent(); return $str; } /** * @return bool */ public function getAllowCustomMethods() { return $this->allowCustomMethods; } /** * @param bool $strictMethods */ public function setAllowCustomMethods($strictMethods) { $this->allowCustomMethods = (bool) $strictMethods; } }
php
BSD-3-Clause
ac4ffd09d509b2c5c0285178c4f7de740f05c3d9
2026-01-05T05:18:13.309357Z
false
zendframework/zend-http
https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/src/Response.php
src/Response.php
<?php /** * @see https://github.com/zendframework/zend-http for the canonical source repository * @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com) * @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License */ namespace Zend\Http; use Zend\Http\Exception\RuntimeException; use Zend\Stdlib\ErrorHandler; use Zend\Stdlib\ResponseInterface; /** * HTTP Response * * @link http://www.w3.org/Protocols/rfc2616/rfc2616-sec6.html#sec6 */ class Response extends AbstractMessage implements ResponseInterface { /**#@+ * @const int Status codes */ const STATUS_CODE_CUSTOM = 0; const STATUS_CODE_100 = 100; const STATUS_CODE_101 = 101; const STATUS_CODE_102 = 102; const STATUS_CODE_200 = 200; const STATUS_CODE_201 = 201; const STATUS_CODE_202 = 202; const STATUS_CODE_203 = 203; const STATUS_CODE_204 = 204; const STATUS_CODE_205 = 205; const STATUS_CODE_206 = 206; const STATUS_CODE_207 = 207; const STATUS_CODE_208 = 208; const STATUS_CODE_226 = 226; const STATUS_CODE_300 = 300; const STATUS_CODE_301 = 301; const STATUS_CODE_302 = 302; const STATUS_CODE_303 = 303; const STATUS_CODE_304 = 304; const STATUS_CODE_305 = 305; const STATUS_CODE_306 = 306; const STATUS_CODE_307 = 307; const STATUS_CODE_308 = 308; const STATUS_CODE_400 = 400; const STATUS_CODE_401 = 401; const STATUS_CODE_402 = 402; const STATUS_CODE_403 = 403; const STATUS_CODE_404 = 404; const STATUS_CODE_405 = 405; const STATUS_CODE_406 = 406; const STATUS_CODE_407 = 407; const STATUS_CODE_408 = 408; const STATUS_CODE_409 = 409; const STATUS_CODE_410 = 410; const STATUS_CODE_411 = 411; const STATUS_CODE_412 = 412; const STATUS_CODE_413 = 413; const STATUS_CODE_414 = 414; const STATUS_CODE_415 = 415; const STATUS_CODE_416 = 416; const STATUS_CODE_417 = 417; const STATUS_CODE_418 = 418; const STATUS_CODE_422 = 422; const STATUS_CODE_423 = 423; const STATUS_CODE_424 = 424; const STATUS_CODE_425 = 425; const STATUS_CODE_426 = 426; const STATUS_CODE_428 = 428; const STATUS_CODE_429 = 429; const STATUS_CODE_431 = 431; const STATUS_CODE_451 = 451; const STATUS_CODE_444 = 444; const STATUS_CODE_499 = 499; const STATUS_CODE_500 = 500; const STATUS_CODE_501 = 501; const STATUS_CODE_502 = 502; const STATUS_CODE_503 = 503; const STATUS_CODE_504 = 504; const STATUS_CODE_505 = 505; const STATUS_CODE_506 = 506; const STATUS_CODE_507 = 507; const STATUS_CODE_508 = 508; const STATUS_CODE_510 = 510; const STATUS_CODE_511 = 511; const STATUS_CODE_599 = 599; /**#@-*/ /** * @internal */ const MIN_STATUS_CODE_VALUE = 100; /** * @internal */ const MAX_STATUS_CODE_VALUE = 599; /** * @var array Recommended Reason Phrases */ protected $recommendedReasonPhrases = [ // INFORMATIONAL CODES 100 => 'Continue', 101 => 'Switching Protocols', 102 => 'Processing', // SUCCESS CODES 200 => 'OK', 201 => 'Created', 202 => 'Accepted', 203 => 'Non-Authoritative Information', 204 => 'No Content', 205 => 'Reset Content', 206 => 'Partial Content', 207 => 'Multi-status', 208 => 'Already Reported', 226 => 'IM Used', // REDIRECTION CODES 300 => 'Multiple Choices', 301 => 'Moved Permanently', 302 => 'Found', 303 => 'See Other', 304 => 'Not Modified', 305 => 'Use Proxy', 306 => 'Switch Proxy', // Deprecated 307 => 'Temporary Redirect', 308 => 'Permanent Redirect', // CLIENT ERROR 400 => 'Bad Request', 401 => 'Unauthorized', 402 => 'Payment Required', 403 => 'Forbidden', 404 => 'Not Found', 405 => 'Method Not Allowed', 406 => 'Not Acceptable', 407 => 'Proxy Authentication Required', 408 => 'Request Time-out', 409 => 'Conflict', 410 => 'Gone', 411 => 'Length Required', 412 => 'Precondition Failed', 413 => 'Request Entity Too Large', 414 => 'Request-URI Too Long', 415 => 'Unsupported Media Type', 416 => 'Requested range not satisfiable', 417 => 'Expectation Failed', 418 => 'I\'m a teapot', 422 => 'Unprocessable Entity', 423 => 'Locked', 424 => 'Failed Dependency', 425 => 'Too Early', 426 => 'Upgrade Required', 428 => 'Precondition Required', 429 => 'Too Many Requests', 431 => 'Request Header Fields Too Large', 444 => 'Connection Closed Without Response', 451 => 'Unavailable For Legal Reasons', 499 => 'Client Closed Request', // SERVER ERROR 500 => 'Internal Server Error', 501 => 'Not Implemented', 502 => 'Bad Gateway', 503 => 'Service Unavailable', 504 => 'Gateway Time-out', 505 => 'HTTP Version not supported', 506 => 'Variant Also Negotiates', 507 => 'Insufficient Storage', 508 => 'Loop Detected', 510 => 'Not Extended', 511 => 'Network Authentication Required', 599 => 'Network Connect Timeout Error', ]; /** * @var int Status code */ protected $statusCode = 200; /** * @var string|null Null means it will be looked up from the $reasonPhrase list above */ protected $reasonPhrase; /** * Populate object from string * * @param string $string * @return static * @throws Exception\InvalidArgumentException */ public static function fromString($string) { $lines = explode("\r\n", $string); if (! is_array($lines) || count($lines) === 1) { $lines = explode("\n", $string); } $firstLine = array_shift($lines); $response = new static(); $response->parseStatusLine($firstLine); /** * @link https://tools.ietf.org/html/rfc7231#section-6.2.1 */ if ($response->statusCode === static::STATUS_CODE_100) { $next = array_shift($lines); // take next line $next = empty($next) ? array_shift($lines) : $next; // take next or skip if empty $response->parseStatusLine($next); } if (count($lines) === 0) { return $response; } $isHeader = true; $headers = $content = []; foreach ($lines as $line) { if ($isHeader && $line === '') { $isHeader = false; continue; } if ($isHeader) { if (preg_match("/[\r\n]/", $line)) { throw new Exception\RuntimeException('CRLF injection detected'); } $headers[] = $line; continue; } if (empty($content) && preg_match('/^[a-z0-9!#$%&\'*+.^_`|~-]+:$/i', $line) ) { throw new Exception\RuntimeException('CRLF injection detected'); } $content[] = $line; } if ($headers) { $response->headers = implode("\r\n", $headers); } if ($content) { $response->setContent(implode("\r\n", $content)); } return $response; } /** * @param string $line * @throws Exception\InvalidArgumentException * @throws Exception\RuntimeException */ protected function parseStatusLine($line) { $regex = '/^HTTP\/(?P<version>1\.[01]|2) (?P<status>\d{3})(?:[ ]+(?P<reason>.*))?$/'; $matches = []; if (! preg_match($regex, $line, $matches)) { throw new Exception\InvalidArgumentException( 'A valid response status line was not found in the provided string' ); } $this->version = $matches['version']; $this->setStatusCode($matches['status']); $this->setReasonPhrase((isset($matches['reason']) ? $matches['reason'] : '')); } /** * @return Header\SetCookie[] */ public function getCookie() { return $this->getHeaders()->get('Set-Cookie'); } /** * Set HTTP status code and (optionally) message * * @param int $code * @throws Exception\InvalidArgumentException * @return $this */ public function setStatusCode($code) { if (! is_numeric($code) || is_float($code) || $code < static::MIN_STATUS_CODE_VALUE || $code > static::MAX_STATUS_CODE_VALUE ) { throw new Exception\InvalidArgumentException(sprintf( 'Invalid status code "%s"; must be an integer between %d and %d, inclusive', is_scalar($code) ? $code : gettype($code), static::MIN_STATUS_CODE_VALUE, static::MAX_STATUS_CODE_VALUE )); } return $this->saveStatusCode($code); } /** * Retrieve HTTP status code * * @return int */ public function getStatusCode() { return $this->statusCode; } /** * Set custom HTTP status code * * @param int $code * @throws Exception\InvalidArgumentException * @return $this */ public function setCustomStatusCode($code) { if (! is_numeric($code)) { $code = is_scalar($code) ? $code : gettype($code); throw new Exception\InvalidArgumentException(sprintf( 'Invalid status code provided: "%s"', $code )); } return $this->saveStatusCode($code); } /** * Assign status code * * @param int $code * @return $this */ protected function saveStatusCode($code) { $this->reasonPhrase = null; $this->statusCode = (int) $code; return $this; } /** * @param string $reasonPhrase * @return $this */ public function setReasonPhrase($reasonPhrase) { $this->reasonPhrase = trim($reasonPhrase); return $this; } /** * Get HTTP status message * * @return string */ public function getReasonPhrase() { if (null == $this->reasonPhrase && isset($this->recommendedReasonPhrases[$this->statusCode])) { $this->reasonPhrase = $this->recommendedReasonPhrases[$this->statusCode]; } return $this->reasonPhrase; } /** * Get the body of the response * * @return string */ public function getBody() { $body = (string) $this->getContent(); $transferEncoding = $this->getHeaders()->get('Transfer-Encoding'); if (! empty($transferEncoding)) { if (strtolower($transferEncoding->getFieldValue()) === 'chunked') { $body = $this->decodeChunkedBody($body); } } $contentEncoding = $this->getHeaders()->get('Content-Encoding'); if (! empty($contentEncoding)) { $contentEncoding = $contentEncoding->getFieldValue(); if ($contentEncoding === 'gzip') { $body = $this->decodeGzip($body); } elseif ($contentEncoding === 'deflate') { $body = $this->decodeDeflate($body); } } return $body; } /** * Does the status code indicate a client error? * * @return bool */ public function isClientError() { $code = $this->getStatusCode(); return ($code < 500 && $code >= 400); } /** * Is the request forbidden due to ACLs? * * @return bool */ public function isForbidden() { return (403 === $this->getStatusCode()); } /** * Is the current status "informational"? * * @return bool */ public function isInformational() { $code = $this->getStatusCode(); return ($code >= 100 && $code < 200); } /** * Does the status code indicate the resource is not found? * * @return bool */ public function isNotFound() { return (404 === $this->getStatusCode()); } /** * Does the status code indicate the resource is gone? * * @return bool */ public function isGone() { return (410 === $this->getStatusCode()); } /** * Do we have a normal, OK response? * * @return bool */ public function isOk() { return (200 === $this->getStatusCode()); } /** * Does the status code reflect a server error? * * @return bool */ public function isServerError() { $code = $this->getStatusCode(); return (500 <= $code && 600 > $code); } /** * Do we have a redirect? * * @return bool */ public function isRedirect() { $code = $this->getStatusCode(); return (300 <= $code && 400 > $code); } /** * Was the response successful? * * @return bool */ public function isSuccess() { $code = $this->getStatusCode(); return (200 <= $code && 300 > $code); } /** * Render the status line header * * @return string */ public function renderStatusLine() { $status = sprintf( 'HTTP/%s %d %s', $this->getVersion(), $this->getStatusCode(), $this->getReasonPhrase() ); return trim($status); } /** * Render entire response as HTTP response string * * @return string */ public function toString() { $str = $this->renderStatusLine() . "\r\n"; $str .= $this->getHeaders()->toString(); $str .= "\r\n"; $str .= $this->getContent(); return $str; } /** * Decode a "chunked" transfer-encoded body and return the decoded text * * @param string $body * @return string * @throws Exception\RuntimeException */ protected function decodeChunkedBody($body) { $decBody = ''; $offset = 0; while (true) { if (! preg_match("/^([\da-fA-F]+)[^\r\n]*\r\n/sm", $body, $m, 0, $offset)) { if (trim(substr($body, $offset))) { // Message was not consumed completely! throw new Exception\RuntimeException( 'Error parsing body - doesn\'t seem to be a chunked message' ); } // Message was consumed completely break; } $length = hexdec(trim($m[1])); $cut = strlen($m[0]); $decBody .= substr($body, $offset + $cut, $length); $offset += $cut + $length + 2; } return $decBody; } /** * Decode a gzip encoded message (when Content-encoding = gzip) * * Currently requires PHP with zlib support * * @param string $body * @return string * @throws Exception\RuntimeException */ protected function decodeGzip($body) { if (! function_exists('gzinflate')) { throw new Exception\RuntimeException( 'zlib extension is required in order to decode "gzip" encoding' ); } if ($body === '' || ($this->getHeaders()->has('content-length') && (int) $this->getHeaders()->get('content-length')->getFieldValue() === 0) ) { return ''; } ErrorHandler::start(); $return = gzinflate(substr($body, 10)); $test = ErrorHandler::stop(); if ($test) { throw new Exception\RuntimeException( 'Error occurred during gzip inflation', 0, $test ); } return $return; } /** * Decode a zlib deflated message (when Content-encoding = deflate) * * Currently requires PHP with zlib support * * @param string $body * @return string * @throws Exception\RuntimeException */ protected function decodeDeflate($body) { if (! function_exists('gzuncompress')) { throw new Exception\RuntimeException( 'zlib extension is required in order to decode "deflate" encoding' ); } if ($this->getHeaders()->has('content-length') && 0 === (int) $this->getHeaders()->get('content-length')->getFieldValue()) { return ''; } /** * Some servers (IIS ?) send a broken deflate response, without the * RFC-required zlib header. * * We try to detect the zlib header, and if it does not exist we * teat the body is plain DEFLATE content. * * This method was adapted from PEAR HTTP_Request2 by (c) Alexey Borzov * * @link http://framework.zend.com/issues/browse/ZF-6040 */ $zlibHeader = unpack('n', substr($body, 0, 2)); if ($zlibHeader[1] % 31 === 0) { return gzuncompress($body); } return gzinflate($body); } }
php
BSD-3-Clause
ac4ffd09d509b2c5c0285178c4f7de740f05c3d9
2026-01-05T05:18:13.309357Z
false
zendframework/zend-http
https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/src/ClientStatic.php
src/ClientStatic.php
<?php /** * @see https://github.com/zendframework/zend-http for the canonical source repository * @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com) * @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License */ namespace Zend\Http; /** * Http static client */ class ClientStatic { /** * @var Client */ protected static $client; /** * Get the static HTTP client * * @param array|Traversable $options * @return Client */ protected static function getStaticClient($options = null) { if (! isset(static::$client) || $options !== null) { static::$client = new Client(null, $options); } return static::$client; } /** * HTTP GET METHOD (static) * * @param string $url * @param array $query * @param array $headers * @param mixed $body * @param array|Traversable $clientOptions * @return Response|bool */ public static function get($url, $query = [], $headers = [], $body = null, $clientOptions = null) { if (empty($url)) { return false; } $request = new Request(); $request->setUri($url); $request->setMethod(Request::METHOD_GET); if (! empty($query) && is_array($query)) { $request->getQuery()->fromArray($query); } if (! empty($headers) && is_array($headers)) { $request->getHeaders()->addHeaders($headers); } if (! empty($body)) { $request->setContent($body); } return static::getStaticClient($clientOptions)->send($request); } /** * HTTP POST METHOD (static) * * @param string $url * @param array $params * @param array $headers * @param mixed $body * @param array|Traversable $clientOptions * @throws Exception\InvalidArgumentException * @return Response|bool */ public static function post($url, $params, $headers = [], $body = null, $clientOptions = null) { if (empty($url)) { return false; } $request = new Request(); $request->setUri($url); $request->setMethod(Request::METHOD_POST); if (! empty($params) && is_array($params)) { $request->getPost()->fromArray($params); } else { throw new Exception\InvalidArgumentException('The array of post parameters is empty'); } if (! isset($headers['Content-Type'])) { $headers['Content-Type'] = Client::ENC_URLENCODED; } if (! empty($headers) && is_array($headers)) { $request->getHeaders()->addHeaders($headers); } if (! empty($body)) { $request->setContent($body); } return static::getStaticClient($clientOptions)->send($request); } }
php
BSD-3-Clause
ac4ffd09d509b2c5c0285178c4f7de740f05c3d9
2026-01-05T05:18:13.309357Z
false
zendframework/zend-http
https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/src/AbstractMessage.php
src/AbstractMessage.php
<?php /** * @see https://github.com/zendframework/zend-http for the canonical source repository * @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com) * @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License */ namespace Zend\Http; use Zend\Stdlib\Message; /** * HTTP standard message (Request/Response) * * @link http://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4 */ abstract class AbstractMessage extends Message { /**#@+ * @const string Version constant numbers */ const VERSION_10 = '1.0'; const VERSION_11 = '1.1'; const VERSION_2 = '2'; /**#@-*/ /** * @var string */ protected $version = self::VERSION_11; /** * @var Headers|null */ protected $headers; /** * Set the HTTP version for this object, one of 1.0, 1.1 or 2 * (AbstractMessage::VERSION_10, AbstractMessage::VERSION_11, AbstractMessage::VERSION_2) * * @param string $version (Must be 1.0, 1.1 or 2) * @return $this * @throws Exception\InvalidArgumentException */ public function setVersion($version) { if (! in_array($version, [self::VERSION_10, self::VERSION_11, self::VERSION_2])) { throw new Exception\InvalidArgumentException( 'Not valid or not supported HTTP version: ' . $version ); } $this->version = $version; return $this; } /** * Return the HTTP version for this request * * @return string */ public function getVersion() { return $this->version; } /** * Provide an alternate Parameter Container implementation for headers in this object, * (this is NOT the primary API for value setting, for that see getHeaders()) * * @see getHeaders() * @param Headers $headers * @return $this */ public function setHeaders(Headers $headers) { $this->headers = $headers; return $this; } /** * Return the header container responsible for headers * * @return Headers */ public function getHeaders() { if ($this->headers === null || is_string($this->headers)) { // this is only here for fromString lazy loading $this->headers = (is_string($this->headers)) ? Headers::fromString($this->headers) : new Headers(); } return $this->headers; } /** * Allow PHP casting of this object * * @return string */ public function __toString() { return $this->toString(); } }
php
BSD-3-Clause
ac4ffd09d509b2c5c0285178c4f7de740f05c3d9
2026-01-05T05:18:13.309357Z
false
zendframework/zend-http
https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/src/HeaderLoader.php
src/HeaderLoader.php
<?php /** * @see https://github.com/zendframework/zend-http for the canonical source repository * @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com) * @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License */ namespace Zend\Http; use Zend\Loader\PluginClassLoader; /** * Plugin Class Loader implementation for HTTP headers */ class HeaderLoader extends PluginClassLoader { /** * @var array Pre-aliased Header plugins */ protected $plugins = [ 'accept' => Header\Accept::class, 'acceptcharset' => Header\AcceptCharset::class, 'acceptencoding' => Header\AcceptEncoding::class, 'acceptlanguage' => Header\AcceptLanguage::class, 'acceptranges' => Header\AcceptRanges::class, 'age' => Header\Age::class, 'allow' => Header\Allow::class, 'authenticationinfo' => Header\AuthenticationInfo::class, 'authorization' => Header\Authorization::class, 'cachecontrol' => Header\CacheControl::class, 'connection' => Header\Connection::class, 'contentdisposition' => Header\ContentDisposition::class, 'contentencoding' => Header\ContentEncoding::class, 'contentlanguage' => Header\ContentLanguage::class, 'contentlength' => Header\ContentLength::class, 'contentlocation' => Header\ContentLocation::class, 'contentmd5' => Header\ContentMD5::class, 'contentrange' => Header\ContentRange::class, 'contentsecuritypolicy' => Header\ContentSecurityPolicy::class, 'contenttransferencoding' => Header\ContentTransferEncoding::class, 'contenttype' => Header\ContentType::class, 'cookie' => Header\Cookie::class, 'date' => Header\Date::class, 'etag' => Header\Etag::class, 'expect' => Header\Expect::class, 'expires' => Header\Expires::class, 'featurepolicy' => Header\FeaturePolicy::class, 'from' => Header\From::class, 'host' => Header\Host::class, 'ifmatch' => Header\IfMatch::class, 'ifmodifiedsince' => Header\IfModifiedSince::class, 'ifnonematch' => Header\IfNoneMatch::class, 'ifrange' => Header\IfRange::class, 'ifunmodifiedsince' => Header\IfUnmodifiedSince::class, 'keepalive' => Header\KeepAlive::class, 'lastmodified' => Header\LastModified::class, 'location' => Header\Location::class, 'maxforwards' => Header\MaxForwards::class, 'origin' => Header\Origin::class, 'pragma' => Header\Pragma::class, 'proxyauthenticate' => Header\ProxyAuthenticate::class, 'proxyauthorization' => Header\ProxyAuthorization::class, 'range' => Header\Range::class, 'referer' => Header\Referer::class, 'refresh' => Header\Refresh::class, 'retryafter' => Header\RetryAfter::class, 'server' => Header\Server::class, 'setcookie' => Header\SetCookie::class, 'te' => Header\TE::class, 'trailer' => Header\Trailer::class, 'transferencoding' => Header\TransferEncoding::class, 'upgrade' => Header\Upgrade::class, 'useragent' => Header\UserAgent::class, 'vary' => Header\Vary::class, 'via' => Header\Via::class, 'warning' => Header\Warning::class, 'wwwauthenticate' => Header\WWWAuthenticate::class, ]; }
php
BSD-3-Clause
ac4ffd09d509b2c5c0285178c4f7de740f05c3d9
2026-01-05T05:18:13.309357Z
false
zendframework/zend-http
https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/src/Headers.php
src/Headers.php
<?php /** * @see https://github.com/zendframework/zend-http for the canonical source repository * @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com) * @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License */ namespace Zend\Http; use ArrayIterator; use Countable; use Iterator; use Traversable; use Zend\Http\Header\Exception; use Zend\Http\Header\GenericHeader; use Zend\Loader\PluginClassLocator; /** * Basic HTTP headers collection functionality * Handles aggregation of headers * * @see http://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.2 */ class Headers implements Countable, Iterator { /** * @var PluginClassLocator */ protected $pluginClassLoader; /** * @var array key names for $headers array */ protected $headersKeys = []; /** * @var array Array of header array information or Header instances */ protected $headers = []; /** * Populates headers from string representation * * Parses a string for headers, and aggregates them, in order, in the * current instance, primarily as strings until they are needed (they * will be lazy loaded) * * @param string $string * @return static * @throws Exception\RuntimeException */ public static function fromString($string) { $headers = new static(); $current = []; $emptyLine = 0; // iterate the header lines, some might be continuations foreach (explode("\r\n", $string) as $line) { // CRLF*2 is end of headers; an empty line by itself or between header lines // is an attempt at CRLF injection. if (preg_match('/^\s*$/', $line)) { // empty line indicates end of headers $emptyLine += 1; if ($emptyLine > 2) { throw new Exception\RuntimeException('Malformed header detected'); } continue; } if ($emptyLine) { throw new Exception\RuntimeException('Malformed header detected'); } // check if a header name is present if (preg_match('/^(?P<name>[^()><@,;:\"\\/\[\]?={} \t]+):.*$/', $line, $matches)) { if ($current) { // a header name was present, then store the current complete line $headers->headersKeys[] = static::createKey($current['name']); $headers->headers[] = $current; } $current = [ 'name' => $matches['name'], 'line' => trim($line), ]; continue; } if (preg_match("/^[ \t][^\r\n]*$/", $line, $matches)) { // continuation: append to current line $current['line'] .= trim($line); continue; } // Line does not match header format! throw new Exception\RuntimeException(sprintf( 'Line "%s" does not match header format!', $line )); } if ($current) { $headers->headersKeys[] = static::createKey($current['name']); $headers->headers[] = $current; } return $headers; } /** * Set an alternate implementation for the PluginClassLoader * * @param PluginClassLocator $pluginClassLoader * @return $this */ public function setPluginClassLoader(PluginClassLocator $pluginClassLoader) { $this->pluginClassLoader = $pluginClassLoader; return $this; } /** * Return an instance of a PluginClassLocator, lazyload and inject map if necessary * * @return PluginClassLocator */ public function getPluginClassLoader() { if ($this->pluginClassLoader === null) { $this->pluginClassLoader = new HeaderLoader(); } return $this->pluginClassLoader; } /** * Add many headers at once * * Expects an array (or Traversable object) of type/value pairs. * * @param array|Traversable $headers * @return $this * @throws Exception\InvalidArgumentException */ public function addHeaders($headers) { if (! is_array($headers) && ! $headers instanceof Traversable) { throw new Exception\InvalidArgumentException(sprintf( 'Expected array or Traversable; received "%s"', (is_object($headers) ? get_class($headers) : gettype($headers)) )); } foreach ($headers as $name => $value) { if (is_int($name)) { if (is_string($value)) { $this->addHeaderLine($value); } elseif (is_array($value) && count($value) == 1) { $this->addHeaderLine(key($value), current($value)); } elseif (is_array($value) && count($value) == 2) { $this->addHeaderLine($value[0], $value[1]); } elseif ($value instanceof Header\HeaderInterface) { $this->addHeader($value); } } elseif (is_string($name)) { $this->addHeaderLine($name, $value); } } return $this; } /** * Add a raw header line, either in name => value, or as a single string 'name: value' * * This method allows for lazy-loading in that the parsing and instantiation of Header object * will be delayed until they are retrieved by either get() or current() * * @throws Exception\InvalidArgumentException * @param string $headerFieldNameOrLine * @param string $fieldValue optional * @return $this */ public function addHeaderLine($headerFieldNameOrLine, $fieldValue = null) { $matches = null; if (preg_match('/^(?P<name>[^()><@,;:\"\\/\[\]?=}{ \t]+):.*$/', $headerFieldNameOrLine, $matches) && $fieldValue === null) { // is a header $headerName = $matches['name']; $headerKey = static::createKey($matches['name']); $line = $headerFieldNameOrLine; } elseif ($fieldValue === null) { throw new Exception\InvalidArgumentException('A field name was provided without a field value'); } else { $headerName = $headerFieldNameOrLine; $headerKey = static::createKey($headerFieldNameOrLine); if (is_array($fieldValue)) { $fieldValue = implode('; ', $fieldValue); } $line = $headerFieldNameOrLine . ': ' . $fieldValue; } $this->headersKeys[] = $headerKey; $this->headers[] = ['name' => $headerName, 'line' => $line]; return $this; } /** * Add a Header to this container, for raw values @see addHeaderLine() and addHeaders() * * @param Header\HeaderInterface $header * @return $this */ public function addHeader(Header\HeaderInterface $header) { $key = static::createKey($header->getFieldName()); $index = array_search($key, $this->headersKeys); // No header by that key presently; append key and header to list. if ($index === false) { $this->headersKeys[] = $key; $this->headers[] = $header; return $this; } // Header exists, and is a multi-value header; append key and header to // list (as multi-value headers are aggregated on retrieval) $class = ($this->getPluginClassLoader()->load(str_replace('-', '', $key))) ?: Header\GenericHeader::class; if (in_array(Header\MultipleHeaderInterface::class, class_implements($class, true))) { $this->headersKeys[] = $key; $this->headers[] = $header; return $this; } // Otherwise, we replace the current instance. $this->headers[$index] = $header; return $this; } /** * Remove a Header from the container * * @param Header\HeaderInterface $header * @return bool */ public function removeHeader(Header\HeaderInterface $header) { $index = array_search($header, $this->headers, true); if ($index !== false) { unset($this->headersKeys[$index]); unset($this->headers[$index]); return true; } return false; } /** * Clear all headers * * Removes all headers from queue * * @return $this */ public function clearHeaders() { $this->headers = $this->headersKeys = []; return $this; } /** * Get all headers of a certain name/type * * @param string $name * @return bool|Header\HeaderInterface|ArrayIterator */ public function get($name) { $key = static::createKey($name); if (! $this->has($name)) { return false; } $class = ($this->getPluginClassLoader()->load(str_replace('-', '', $key))) ?: 'Zend\Http\Header\GenericHeader'; if (in_array('Zend\Http\Header\MultipleHeaderInterface', class_implements($class, true))) { $headers = []; foreach (array_keys($this->headersKeys, $key) as $index) { if (is_array($this->headers[$index])) { $this->lazyLoadHeader($index); } } foreach (array_keys($this->headersKeys, $key) as $index) { $headers[] = $this->headers[$index]; } return new ArrayIterator($headers); } $index = array_search($key, $this->headersKeys); if ($index === false) { return false; } if (is_array($this->headers[$index])) { return $this->lazyLoadHeader($index); } return $this->headers[$index]; } /** * Test for existence of a type of header * * @param string $name * @return bool */ public function has($name) { return in_array(static::createKey($name), $this->headersKeys); } /** * Advance the pointer for this object as an iterator * * @return void */ public function next() { next($this->headers); } /** * Return the current key for this object as an iterator * * @return mixed */ public function key() { return (key($this->headers)); } /** * Is this iterator still valid? * * @return bool */ public function valid() { return (current($this->headers) !== false); } /** * Reset the internal pointer for this object as an iterator * * @return void */ public function rewind() { reset($this->headers); } /** * Return the current value for this iterator, lazy loading it if need be * * @return array|Header\HeaderInterface */ public function current() { $current = current($this->headers); if (is_array($current)) { $current = $this->lazyLoadHeader(key($this->headers)); } return $current; } /** * Return the number of headers in this contain, if all headers have not been parsed, actual count could * increase if MultipleHeader objects exist in the Request/Response. If you need an exact count, iterate * * @return int count of currently known headers */ public function count() { return count($this->headers); } /** * Render all headers at once * * This method handles the normal iteration of headers; it is up to the * concrete classes to prepend with the appropriate status/request line. * * @return string */ public function toString() { $headers = ''; foreach ($this->toArray() as $fieldName => $fieldValue) { if (is_array($fieldValue)) { // Handle multi-value headers foreach ($fieldValue as $value) { $headers .= $fieldName . ': ' . $value . "\r\n"; } continue; } // Handle single-value headers $headers .= $fieldName . ': ' . $fieldValue . "\r\n"; } return $headers; } /** * Return the headers container as an array * * @todo determine how to produce single line headers, if they are supported * @return array */ public function toArray() { $headers = []; /* @var $header Header\HeaderInterface */ foreach ($this->headers as $index => $header) { if (is_array($header)) { $header = $this->lazyLoadHeader($index); } if ($header instanceof Header\MultipleHeaderInterface) { $name = $header->getFieldName(); if (! isset($headers[$name])) { $headers[$name] = []; } $headers[$name][] = $header->getFieldValue(); } else { $headers[$header->getFieldName()] = $header->getFieldValue(); } } return $headers; } /** * By calling this, it will force parsing and loading of all headers, after this count() will be accurate * * @return bool */ public function forceLoading() { foreach ($this as $item) { // $item should now be loaded } return true; } /** * @param $index * @param bool $isGeneric If true, there is no need to parse $index and call the ClassLoader. * @return mixed|void */ protected function lazyLoadHeader($index, $isGeneric = false) { $current = $this->headers[$index]; $key = $this->headersKeys[$index]; /* @var $class Header\HeaderInterface */ $class = $this->getPluginClassLoader()->load(str_replace('-', '', $key)); if ($isGeneric || ! $class) { $class = GenericHeader::class; } try { $headers = $class::fromString($current['line']); } catch (Exception\InvalidArgumentException $exception) { // Generic Header should throw an exception if it fails if ($isGeneric) { throw $exception; } // Retry one more time with GenericHeader return $this->lazyLoadHeader($index, true); } if (is_array($headers)) { $this->headers[$index] = $current = array_shift($headers); foreach ($headers as $header) { $this->headersKeys[] = $key; $this->headers[] = $header; } return $current; } $this->headers[$index] = $current = $headers; return $current; } /** * Create array key from header name * * @param string $name * @return string */ protected static function createKey($name) { return str_replace(['_', ' ', '.'], '-', strtolower($name)); } }
php
BSD-3-Clause
ac4ffd09d509b2c5c0285178c4f7de740f05c3d9
2026-01-05T05:18:13.309357Z
false
zendframework/zend-http
https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/src/Cookies.php
src/Cookies.php
<?php /** * @see https://github.com/zendframework/zend-http for the canonical source repository * @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com) * @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License */ namespace Zend\Http; use ArrayIterator; use Zend\Http\Header\SetCookie; use Zend\Uri; /** * A Zend\Http\Cookies object is designed to contain and maintain HTTP cookies, and should * be used along with Zend\Http\Client in order to manage cookies across HTTP requests and * responses. * * The class contains an array of Zend\Http\Header\Cookie objects. Cookies can be added * automatically from a request or manually. Then, the Cookies class can find and return the * cookies needed for a specific HTTP request. * * A special parameter can be passed to all methods of this class that return cookies: Cookies * can be returned either in their native form (as Zend\Http\Header\Cookie objects) or as strings - * the later is suitable for sending as the value of the "Cookie" header in an HTTP request. * You can also choose, when returning more than one cookie, whether to get an array of strings * (by passing Zend\Http\Client\Cookies::COOKIE_STRING_ARRAY) or one unified string for all cookies * (by passing Zend\Http\Client\Cookies::COOKIE_STRING_CONCAT). * * @link http://wp.netscape.com/newsref/std/cookie_spec.html for some specs. */ class Cookies extends Headers { /** * Return cookie(s) as a Zend\Http\Cookie object */ const COOKIE_OBJECT = 0; /** * Return cookie(s) as a string (suitable for sending in an HTTP request) */ const COOKIE_STRING_ARRAY = 1; /** * Return all cookies as one long string (suitable for sending in an HTTP request) */ const COOKIE_STRING_CONCAT = 2; /** * Return all cookies as one long string (strict mode) * - Single space after the semi-colon separating each cookie * - Remove trailing semi-colon, if any */ const COOKIE_STRING_CONCAT_STRICT = 3; /** * @var array */ protected $cookies = []; /** * @var \Zend\Http\Headers */ protected $headers; /** * @var array */ protected $rawCookies; /** * @static * @throws Exception\RuntimeException * @param $string * @return void */ public static function fromString($string) { throw new Exception\RuntimeException( __CLASS__ . '::' . __FUNCTION__ . ' should not be used as a factory, use ' . __NAMESPACE__ . '\Headers::fromString() instead.' ); } /** * Add a cookie to the class. Cookie should be passed either as a Zend\Http\Header\SetCookie object * or as a string - in which case an object is created from the string. * * @param SetCookie|string $cookie * @param Uri\Uri|string $refUri Optional reference URI (for domain, path, secure) * @throws Exception\InvalidArgumentException */ public function addCookie($cookie, $refUri = null) { if (is_string($cookie)) { $cookie = SetCookie::fromString($cookie, $refUri); } if ($cookie instanceof SetCookie) { $domain = $cookie->getDomain(); $path = $cookie->getPath(); if (! isset($this->cookies[$domain])) { $this->cookies[$domain] = []; } if (! isset($this->cookies[$domain][$path])) { $this->cookies[$domain][$path] = []; } $this->cookies[$domain][$path][$cookie->getName()] = $cookie; $this->rawCookies[] = $cookie; } else { throw new Exception\InvalidArgumentException('Supplient argument is not a valid cookie string or object'); } } /** * Parse an HTTP response, adding all the cookies set in that response * * @param Response $response * @param Uri\Uri|string $refUri Requested URI */ public function addCookiesFromResponse(Response $response, $refUri) { $cookieHdrs = $response->getHeaders()->get('Set-Cookie'); if (is_array($cookieHdrs) || $cookieHdrs instanceof ArrayIterator) { foreach ($cookieHdrs as $cookie) { $this->addCookie($cookie, $refUri); } } elseif (is_string($cookieHdrs)) { $this->addCookie($cookieHdrs, $refUri); } } /** * Get all cookies in the cookie jar as an array * * @param int $retAs Whether to return cookies as objects of \Zend\Http\Header\SetCookie or as strings * @return array|string */ public function getAllCookies($retAs = self::COOKIE_OBJECT) { $cookies = $this->_flattenCookiesArray($this->cookies, $retAs); return $cookies; } /** * Return an array of all cookies matching a specific request according to the request URI, * whether session cookies should be sent or not, and the time to consider as "now" when * checking cookie expiry time. * * @param string|Uri\Uri $uri URI to check against (secure, domain, path) * @param bool $matchSessionCookies Whether to send session cookies * @param int $retAs Whether to return cookies as objects of \Zend\Http\Header\Cookie or as strings * @param int $now Override the current time when checking for expiry time * @throws Exception\InvalidArgumentException if invalid URI specified * @return array|string */ public function getMatchingCookies( $uri, $matchSessionCookies = true, $retAs = self::COOKIE_OBJECT, $now = null ) { if (is_string($uri)) { $uri = Uri\UriFactory::factory($uri, 'http'); } elseif (! $uri instanceof Uri\Uri) { throw new Exception\InvalidArgumentException('Invalid URI string or object passed'); } $host = $uri->getHost(); if (empty($host)) { throw new Exception\InvalidArgumentException('Invalid URI specified; does not contain a host'); } // First, reduce the array of cookies to only those matching domain and path $cookies = $this->_matchDomain($host); $cookies = $this->_matchPath($cookies, $uri->getPath()); $cookies = $this->_flattenCookiesArray($cookies, self::COOKIE_OBJECT); // Next, run Cookie->match on all cookies to check secure, time and session matching $ret = []; foreach ($cookies as $cookie) { if ($cookie->match($uri, $matchSessionCookies, $now)) { $ret[] = $cookie; } } // Now, use self::_flattenCookiesArray again - only to convert to the return format ;) $ret = $this->_flattenCookiesArray($ret, $retAs); return $ret; } /** * Get a specific cookie according to a URI and name * * @param Uri\Uri|string $uri The uri (domain and path) to match * @param string $cookieName The cookie's name * @param int $retAs Whether to return cookies as objects of \Zend\Http\Header\SetCookie or as strings * @throws Exception\InvalidArgumentException if invalid URI specified or invalid $retAs value * @return SetCookie|string */ public function getCookie($uri, $cookieName, $retAs = self::COOKIE_OBJECT) { if (is_string($uri)) { $uri = Uri\UriFactory::factory($uri, 'http'); } elseif (! $uri instanceof Uri\Uri) { throw new Exception\InvalidArgumentException('Invalid URI specified'); } $host = $uri->getHost(); if (empty($host)) { throw new Exception\InvalidArgumentException('Invalid URI specified; host missing'); } // Get correct cookie path $path = $uri->getPath(); $lastSlashPos = strrpos($path, '/') ?: 0; $path = substr($path, 0, $lastSlashPos); if (! $path) { $path = '/'; } if (isset($this->cookies[$uri->getHost()][$path][$cookieName])) { $cookie = $this->cookies[$uri->getHost()][$path][$cookieName]; switch ($retAs) { case self::COOKIE_OBJECT: return $cookie; case self::COOKIE_STRING_ARRAY: case self::COOKIE_STRING_CONCAT: return $cookie->__toString(); default: throw new Exception\InvalidArgumentException(sprintf( 'Invalid value passed for $retAs: %s', $retAs )); } } return false; } /** * Helper function to recursively flatten an array. Should be used when exporting the * cookies array (or parts of it) * * @param \Zend\Http\Header\SetCookie|array $ptr * @param int $retAs What value to return * @return array|string */ // @codingStandardsIgnoreStart protected function _flattenCookiesArray($ptr, $retAs = self::COOKIE_OBJECT) { // @codingStandardsIgnoreEnd if (is_array($ptr)) { $ret = ($retAs == self::COOKIE_STRING_CONCAT ? '' : []); foreach ($ptr as $item) { if ($retAs == self::COOKIE_STRING_CONCAT) { $ret .= $this->_flattenCookiesArray($item, $retAs); } else { $ret = array_merge($ret, $this->_flattenCookiesArray($item, $retAs)); } } return $ret; } elseif ($ptr instanceof SetCookie) { switch ($retAs) { case self::COOKIE_STRING_ARRAY: return [$ptr->__toString()]; case self::COOKIE_STRING_CONCAT: return $ptr->__toString(); case self::COOKIE_OBJECT: default: return [$ptr]; } } return; } /** * Return a subset of the cookies array matching a specific domain * * @param string $domain * @return array */ // @codingStandardsIgnoreStart protected function _matchDomain($domain) { // @codingStandardsIgnoreEnd $ret = []; foreach (array_keys($this->cookies) as $cdom) { if (SetCookie::matchCookieDomain($cdom, $domain)) { $ret[$cdom] = $this->cookies[$cdom]; } } return $ret; } /** * Return a subset of a domain-matching cookies that also match a specified path * * @param array $domains * @param string $path * @return array */ // @codingStandardsIgnoreStart protected function _matchPath($domains, $path) { // @codingStandardsIgnoreEnd $ret = []; foreach ($domains as $dom => $pathsArray) { foreach (array_keys($pathsArray) as $cpath) { if (SetCookie::matchCookiePath($cpath, $path)) { if (! isset($ret[$dom])) { $ret[$dom] = []; } $ret[$dom][$cpath] = $pathsArray[$cpath]; } } } return $ret; } /** * Create a new Cookies object and automatically load into it all the * cookies set in a Response object. If $uri is set, it will be * considered as the requested URI for setting default domain and path * of the cookie. * * @param Response $response HTTP Response object * @param Uri\Uri|string $refUri The requested URI * @return static * @todo Add the $uri functionality. */ public static function fromResponse(Response $response, $refUri) { $jar = new static(); $jar->addCookiesFromResponse($response, $refUri); return $jar; } /** * Tells if the array of cookies is empty * * @return bool */ public function isEmpty() { return count($this) == 0; } /** * Empties the cookieJar of any cookie * * @return $this */ public function reset() { $this->cookies = $this->rawCookies = []; return $this; } }
php
BSD-3-Clause
ac4ffd09d509b2c5c0285178c4f7de740f05c3d9
2026-01-05T05:18:13.309357Z
false
zendframework/zend-http
https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/src/Client/Exception/OutOfRangeException.php
src/Client/Exception/OutOfRangeException.php
<?php /** * @see https://github.com/zendframework/zend-http for the canonical source repository * @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com) * @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License */ namespace Zend\Http\Client\Exception; use Zend\Http\Exception; class OutOfRangeException extends Exception\OutOfRangeException implements ExceptionInterface { }
php
BSD-3-Clause
ac4ffd09d509b2c5c0285178c4f7de740f05c3d9
2026-01-05T05:18:13.309357Z
false
zendframework/zend-http
https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/src/Client/Exception/ExceptionInterface.php
src/Client/Exception/ExceptionInterface.php
<?php /** * @see https://github.com/zendframework/zend-http for the canonical source repository * @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com) * @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License */ namespace Zend\Http\Client\Exception; use Zend\Http\Exception\ExceptionInterface as HttpException; interface ExceptionInterface extends HttpException { }
php
BSD-3-Clause
ac4ffd09d509b2c5c0285178c4f7de740f05c3d9
2026-01-05T05:18:13.309357Z
false
zendframework/zend-http
https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/src/Client/Exception/RuntimeException.php
src/Client/Exception/RuntimeException.php
<?php /** * @see https://github.com/zendframework/zend-http for the canonical source repository * @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com) * @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License */ namespace Zend\Http\Client\Exception; use Zend\Http\Exception; class RuntimeException extends Exception\RuntimeException implements ExceptionInterface { }
php
BSD-3-Clause
ac4ffd09d509b2c5c0285178c4f7de740f05c3d9
2026-01-05T05:18:13.309357Z
false
zendframework/zend-http
https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/src/Client/Exception/InvalidArgumentException.php
src/Client/Exception/InvalidArgumentException.php
<?php /** * @see https://github.com/zendframework/zend-http for the canonical source repository * @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com) * @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License */ namespace Zend\Http\Client\Exception; use Zend\Http\Exception; class InvalidArgumentException extends Exception\InvalidArgumentException implements ExceptionInterface { }
php
BSD-3-Clause
ac4ffd09d509b2c5c0285178c4f7de740f05c3d9
2026-01-05T05:18:13.309357Z
false
zendframework/zend-http
https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/src/Client/Adapter/Proxy.php
src/Client/Adapter/Proxy.php
<?php /** * @see https://github.com/zendframework/zend-http for the canonical source repository * @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com) * @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License */ namespace Zend\Http\Client\Adapter; use Traversable; use Zend\Http\Client; use Zend\Http\Client\Adapter\Exception as AdapterException; use Zend\Http\Response; use Zend\Stdlib\ArrayUtils; use Zend\Stdlib\ErrorHandler; /** * HTTP Proxy-supporting Zend\Http\Client adapter class, based on the default * socket based adapter. * * Should be used if proxy HTTP access is required. If no proxy is set, will * fall back to Zend\Http\Client\Adapter\Socket behavior. Just like the * default Socket adapter, this adapter does not require any special extensions * installed. */ class Proxy extends Socket { /** * Parameters array * * @var array */ protected $config = [ 'persistent' => false, 'ssltransport' => 'ssl', 'sslcert' => null, 'sslpassphrase' => null, 'sslverifypeer' => true, 'sslcafile' => null, 'sslcapath' => null, 'sslallowselfsigned' => false, 'sslusecontext' => false, 'sslverifypeername' => true, 'proxy_host' => '', 'proxy_port' => 8080, 'proxy_user' => '', 'proxy_pass' => '', 'proxy_auth' => Client::AUTH_BASIC, ]; /** * Whether HTTPS CONNECT was already negotiated with the proxy or not * * @var bool */ protected $negotiated = false; /** * Set the configuration array for the adapter * * @param array $options */ public function setOptions($options = []) { if ($options instanceof Traversable) { $options = ArrayUtils::iteratorToArray($options); } if (! is_array($options)) { throw new AdapterException\InvalidArgumentException( 'Array or Zend\Config object expected, got ' . gettype($options) ); } //enforcing that the proxy keys are set in the form proxy_* foreach ($options as $k => $v) { if (preg_match('/^proxy[a-z]+/', $k)) { $options['proxy_' . substr($k, 5, strlen($k))] = $v; unset($options[$k]); } } parent::setOptions($options); } /** * Connect to the remote server * * Will try to connect to the proxy server. If no proxy was set, will * fall back to the target server (behave like regular Socket adapter) * * @param string $host * @param int $port * @param bool $secure * @throws AdapterException\RuntimeException */ public function connect($host, $port = 80, $secure = false) { // If no proxy is set, fall back to Socket adapter if (! $this->config['proxy_host']) { parent::connect($host, $port, $secure); return; } /* Url might require stream context even if proxy connection doesn't */ if ($secure) { $this->config['sslusecontext'] = true; $this->setSslCryptoMethod = false; } // Connect (a non-secure connection) to the proxy server parent::connect( $this->config['proxy_host'], $this->config['proxy_port'], false ); } /** * Send request to the proxy server * * @param string $method * @param \Zend\Uri\Uri $uri * @param string $httpVer * @param array $headers * @param string $body * @throws AdapterException\RuntimeException * @return string Request as string */ public function write($method, $uri, $httpVer = '1.1', $headers = [], $body = '') { // If no proxy is set, fall back to default Socket adapter if (! $this->config['proxy_host']) { return parent::write($method, $uri, $httpVer, $headers, $body); } // Make sure we're properly connected if (! $this->socket) { throw new AdapterException\RuntimeException('Trying to write but we are not connected'); } $host = $this->config['proxy_host']; $port = $this->config['proxy_port']; $isSecure = strtolower($uri->getScheme()) === 'https'; $connectedHost = ($isSecure ? $this->config['ssltransport'] : 'tcp') . '://' . $host; if ($this->connectedTo[1] !== $port || $this->connectedTo[0] !== $connectedHost) { throw new AdapterException\RuntimeException( 'Trying to write but we are connected to the wrong proxy server' ); } // Add Proxy-Authorization header if ($this->config['proxy_user'] && ! isset($headers['proxy-authorization'])) { $headers['proxy-authorization'] = Client::encodeAuthHeader( $this->config['proxy_user'], $this->config['proxy_pass'], $this->config['proxy_auth'] ); } // if we are proxying HTTPS, preform CONNECT handshake with the proxy if ($isSecure && ! $this->negotiated) { $this->connectHandshake($uri->getHost(), $uri->getPort(), $httpVer, $headers); $this->negotiated = true; } // Save request method for later $this->method = $method; if ($uri->getUserInfo()) { $headers['Authorization'] = 'Basic ' . base64_encode($uri->getUserInfo()); } $path = $uri->getPath(); $query = $uri->getQuery(); $path .= $query ? '?' . $query : ''; if (! $this->negotiated) { $path = $uri->getScheme() . '://' . $uri->getHost() . $path; } // Build request headers $request = sprintf('%s %s HTTP/%s%s', $method, $path, $httpVer, "\r\n"); // Add all headers to the request string foreach ($headers as $k => $v) { if (is_string($k)) { $v = $k . ': ' . $v; } $request .= $v . "\r\n"; } if (is_resource($body)) { $request .= "\r\n"; } else { // Add the request body $request .= "\r\n" . $body; } // Send the request ErrorHandler::start(); $test = fwrite($this->socket, $request); $error = ErrorHandler::stop(); if ($test === false) { throw new AdapterException\RuntimeException('Error writing request to proxy server', 0, $error); } if (is_resource($body)) { if (stream_copy_to_stream($body, $this->socket) == 0) { throw new AdapterException\RuntimeException('Error writing request to server'); } } return $request; } /** * Preform handshaking with HTTPS proxy using CONNECT method * * @param string $host * @param int $port * @param string $httpVer * @param array $headers * @throws AdapterException\RuntimeException */ protected function connectHandshake($host, $port = 443, $httpVer = '1.1', array &$headers = []) { $request = 'CONNECT ' . $host . ':' . $port . ' HTTP/' . $httpVer . "\r\n" . 'Host: ' . $host . "\r\n"; // Add the user-agent header if (isset($this->config['useragent'])) { $request .= 'User-agent: ' . $this->config['useragent'] . "\r\n"; } // If the proxy-authorization header is set, send it to proxy but remove // it from headers sent to target host if (isset($headers['proxy-authorization'])) { $request .= 'Proxy-authorization: ' . $headers['proxy-authorization'] . "\r\n"; unset($headers['proxy-authorization']); } $request .= "\r\n"; // Send the request ErrorHandler::start(); $test = fwrite($this->socket, $request); $error = ErrorHandler::stop(); if (! $test) { throw new AdapterException\RuntimeException('Error writing request to proxy server', 0, $error); } // Read response headers only $response = ''; $gotStatus = false; ErrorHandler::start(); while ($line = fgets($this->socket)) { $gotStatus = $gotStatus || (strpos($line, 'HTTP') !== false); if ($gotStatus) { $response .= $line; if (! rtrim($line)) { break; } } } ErrorHandler::stop(); // Check that the response from the proxy is 200 if (Response::fromString($response)->getStatusCode() != 200) { throw new AdapterException\RuntimeException(sprintf( 'Unable to connect to HTTPS proxy. Server response: %s', $response )); } // If all is good, switch socket to secure mode. We have to fall back // through the different modes $modes = [ STREAM_CRYPTO_METHOD_TLS_CLIENT, STREAM_CRYPTO_METHOD_SSLv3_CLIENT, STREAM_CRYPTO_METHOD_SSLv23_CLIENT, STREAM_CRYPTO_METHOD_SSLv2_CLIENT, ]; $success = false; foreach ($modes as $mode) { $success = stream_socket_enable_crypto($this->socket, true, $mode); if ($success) { break; } } if (! $success) { throw new AdapterException\RuntimeException( 'Unable to connect to HTTPS server through proxy: could not negotiate secure connection.' ); } } /** * Close the connection to the server */ public function close() { parent::close(); $this->negotiated = false; } /** * Destructor: make sure the socket is disconnected */ public function __destruct() { if ($this->socket) { $this->close(); } } }
php
BSD-3-Clause
ac4ffd09d509b2c5c0285178c4f7de740f05c3d9
2026-01-05T05:18:13.309357Z
false
zendframework/zend-http
https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/src/Client/Adapter/Socket.php
src/Client/Adapter/Socket.php
<?php /** * @see https://github.com/zendframework/zend-http for the canonical source repository * @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com) * @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License */ namespace Zend\Http\Client\Adapter; use Traversable; use Zend\Http\Client\Adapter\AdapterInterface as HttpAdapter; use Zend\Http\Client\Adapter\Exception as AdapterException; use Zend\Http\Request; use Zend\Http\Response; use Zend\Stdlib\ArrayUtils; use Zend\Stdlib\ErrorHandler; /** * A sockets based (stream\socket\client) adapter class for Zend\Http\Client. Can be used * on almost every PHP environment, and does not require any special extensions. */ class Socket implements HttpAdapter, StreamInterface { /** * Map SSL transport wrappers to stream crypto method constants * * @var array */ protected static $sslCryptoTypes = [ 'ssl' => STREAM_CRYPTO_METHOD_SSLv23_CLIENT, 'sslv2' => STREAM_CRYPTO_METHOD_SSLv2_CLIENT, 'sslv3' => STREAM_CRYPTO_METHOD_SSLv3_CLIENT, 'tls' => STREAM_CRYPTO_METHOD_TLS_CLIENT, ]; /** * The socket for server connection * * @var resource|null */ protected $socket; /** * What host/port are we connected to? * * @var array */ protected $connectedTo = [null, null]; /** * Stream for storing output * * @var resource */ protected $outStream; /** * Parameters array * * @var array */ protected $config = [ 'persistent' => false, 'ssltransport' => 'ssl', 'sslcert' => null, 'sslpassphrase' => null, 'sslverifypeer' => true, 'sslcafile' => null, 'sslcapath' => null, 'sslallowselfsigned' => false, 'sslusecontext' => false, 'sslverifypeername' => true, ]; /** * Request method - will be set by write() and might be used by read() * * @var string */ protected $method; /** * Stream context * * @var resource */ protected $context; /** * @var bool */ protected $setSslCryptoMethod = true; /** * Adapter constructor, currently empty. Config is set using setOptions() * */ public function __construct() { } /** * Set the configuration array for the adapter * * @param array|Traversable $options * @throws AdapterException\InvalidArgumentException */ public function setOptions($options = []) { if ($options instanceof Traversable) { $options = ArrayUtils::iteratorToArray($options); } if (! is_array($options)) { throw new AdapterException\InvalidArgumentException( 'Array or Zend\Config object expected, got ' . gettype($options) ); } foreach ($options as $k => $v) { $this->config[strtolower($k)] = $v; } } /** * Retrieve the array of all configuration options * * @return array */ public function getConfig() { return $this->config; } /** * Set the stream context for the TCP connection to the server * * Can accept either a pre-existing stream context resource, or an array * of stream options, similar to the options array passed to the * stream_context_create() PHP function. In such case a new stream context * will be created using the passed options. * * @since Zend Framework 1.9 * * @param mixed $context Stream context or array of context options * @throws Exception\InvalidArgumentException * @return $this */ public function setStreamContext($context) { if (is_resource($context) && get_resource_type($context) == 'stream-context') { $this->context = $context; } elseif (is_array($context)) { $this->context = stream_context_create($context); } else { // Invalid parameter throw new AdapterException\InvalidArgumentException(sprintf( 'Expecting either a stream context resource or array, got %s', gettype($context) )); } return $this; } /** * Get the stream context for the TCP connection to the server. * * If no stream context is set, will create a default one. * * @return resource */ public function getStreamContext() { if (! $this->context) { $this->context = stream_context_create(); } return $this->context; } /** * Connect to the remote server * * @param string $host * @param int $port * @param bool $secure * @throws AdapterException\RuntimeException */ public function connect($host, $port = 80, $secure = false) { // If we are connected to the wrong host, disconnect first $connectedHost = (strpos($this->connectedTo[0], '://')) ? substr($this->connectedTo[0], (strpos($this->connectedTo[0], '://') + 3), strlen($this->connectedTo[0])) : $this->connectedTo[0]; if ($connectedHost != $host || $this->connectedTo[1] != $port) { if (is_resource($this->socket)) { $this->close(); } } // Now, if we are not connected, connect if (! is_resource($this->socket) || ! $this->config['keepalive']) { $context = $this->getStreamContext(); if ($secure || $this->config['sslusecontext']) { if ($this->config['sslverifypeer'] !== null) { if (! stream_context_set_option($context, 'ssl', 'verify_peer', $this->config['sslverifypeer'])) { throw new AdapterException\RuntimeException('Unable to set sslverifypeer option'); } } if ($this->config['sslcafile']) { if (! stream_context_set_option($context, 'ssl', 'cafile', $this->config['sslcafile'])) { throw new AdapterException\RuntimeException('Unable to set sslcafile option'); } } if ($this->config['sslcapath']) { if (! stream_context_set_option($context, 'ssl', 'capath', $this->config['sslcapath'])) { throw new AdapterException\RuntimeException('Unable to set sslcapath option'); } } if ($this->config['sslallowselfsigned'] !== null) { if (! stream_context_set_option( $context, 'ssl', 'allow_self_signed', $this->config['sslallowselfsigned'] )) { throw new AdapterException\RuntimeException('Unable to set sslallowselfsigned option'); } } if ($this->config['sslcert'] !== null) { if (! stream_context_set_option($context, 'ssl', 'local_cert', $this->config['sslcert'])) { throw new AdapterException\RuntimeException('Unable to set sslcert option'); } } if ($this->config['sslpassphrase'] !== null) { if (! stream_context_set_option($context, 'ssl', 'passphrase', $this->config['sslpassphrase'])) { throw new AdapterException\RuntimeException('Unable to set sslpassphrase option'); } } if ($this->config['sslverifypeername'] !== null) { if (! stream_context_set_option( $context, 'ssl', 'verify_peer_name', $this->config['sslverifypeername'] )) { throw new AdapterException\RuntimeException('Unable to set sslverifypeername option'); } } } $flags = STREAM_CLIENT_CONNECT; if ($this->config['persistent']) { $flags |= STREAM_CLIENT_PERSISTENT; } if (isset($this->config['connecttimeout'])) { $connectTimeout = $this->config['connecttimeout']; } else { $connectTimeout = $this->config['timeout']; } if ($connectTimeout !== null && ! is_numeric($connectTimeout)) { throw new AdapterException\InvalidArgumentException(sprintf( 'integer or numeric string expected, got %s', gettype($connectTimeout) )); } ErrorHandler::start(); $this->socket = stream_socket_client( $host . ':' . $port, $errno, $errstr, (int) $connectTimeout, $flags, $context ); $error = ErrorHandler::stop(); if (! $this->socket) { $this->close(); throw new AdapterException\RuntimeException( sprintf( 'Unable to connect to %s:%d%s', $host, $port, ($error ? ' . Error #' . $error->getCode() . ': ' . $error->getMessage() : '') ), 0, $error ); } // Set the stream timeout if (! stream_set_timeout($this->socket, (int) $this->config['timeout'])) { throw new AdapterException\RuntimeException('Unable to set the connection timeout'); } if ($secure || $this->config['sslusecontext']) { if ($this->setSslCryptoMethod) { if ($this->config['ssltransport'] && isset(static::$sslCryptoTypes[$this->config['ssltransport']]) ) { $sslCryptoMethod = static::$sslCryptoTypes[$this->config['ssltransport']]; } else { $sslCryptoMethod = STREAM_CRYPTO_METHOD_SSLv3_CLIENT; } ErrorHandler::start(); $test = stream_socket_enable_crypto($this->socket, true, $sslCryptoMethod); $error = ErrorHandler::stop(); if (! $test || $error) { // Error handling is kind of difficult when it comes to SSL $errorString = ''; if (extension_loaded('openssl')) { while (($sslError = openssl_error_string()) != false) { $errorString .= sprintf('; SSL error: %s', $sslError); } } $this->close(); if ((! $errorString) && $this->config['sslverifypeer']) { // There's good chance our error is due to sslcapath not being properly set if (! ($this->config['sslcafile'] || $this->config['sslcapath'])) { $errorString = 'make sure the "sslcafile" or "sslcapath" option are properly set for ' . 'the environment.'; } elseif ($this->config['sslcafile'] && ! is_file($this->config['sslcafile'])) { $errorString = 'make sure the "sslcafile" option points to a valid SSL certificate ' . 'file'; } elseif ($this->config['sslcapath'] && ! is_dir($this->config['sslcapath'])) { $errorString = 'make sure the "sslcapath" option points to a valid SSL certificate ' . 'directory'; } } if ($errorString) { $errorString = sprintf(': %s', $errorString); } throw new AdapterException\RuntimeException(sprintf( 'Unable to enable crypto on TCP connection %s%s', $host, $errorString ), 0, $error); } } $host = $this->config['ssltransport'] . '://' . $host; } else { $host = 'tcp://' . $host; } // Update connectedTo $this->connectedTo = [$host, $port]; } } /** * Send request to the remote server * * @param string $method * @param \Zend\Uri\Uri $uri * @param string $httpVer * @param array $headers * @param string $body * @throws AdapterException\RuntimeException * @return string Request as string */ public function write($method, $uri, $httpVer = '1.1', $headers = [], $body = '') { // Make sure we're properly connected if (! $this->socket) { throw new AdapterException\RuntimeException('Trying to write but we are not connected'); } $host = $uri->getHost(); $host = (strtolower($uri->getScheme()) == 'https' ? $this->config['ssltransport'] : 'tcp') . '://' . $host; if ($this->connectedTo[0] != $host || $this->connectedTo[1] != $uri->getPort()) { throw new AdapterException\RuntimeException('Trying to write but we are connected to the wrong host'); } // Save request method for later $this->method = $method; // Build request headers $path = $uri->getPath(); $query = $uri->getQuery(); $path .= $query ? '?' . $query : ''; $request = $method . ' ' . $path . ' HTTP/' . $httpVer . "\r\n"; foreach ($headers as $k => $v) { if (is_string($k)) { $v = $k . ': ' . $v; } $request .= $v . "\r\n"; } if (is_resource($body)) { $request .= "\r\n"; } else { // Add the request body $request .= "\r\n" . $body; } // Send the request ErrorHandler::start(); $test = fwrite($this->socket, $request); $error = ErrorHandler::stop(); if (false === $test) { throw new AdapterException\RuntimeException('Error writing request to server', 0, $error); } if (is_resource($body)) { if (stream_copy_to_stream($body, $this->socket) == 0) { throw new AdapterException\RuntimeException('Error writing request to server'); } } return $request; } /** * Read response from server * * @throws AdapterException\RuntimeException * @return string */ public function read() { // First, read headers only $response = ''; $gotStatus = false; while (($line = fgets($this->socket)) !== false) { $gotStatus = $gotStatus || (strpos($line, 'HTTP') !== false); if ($gotStatus) { $response .= $line; if (rtrim($line) === '') { break; } } } $this->_checkSocketReadTimeout(); $responseObj = Response::fromString($response); $statusCode = $responseObj->getStatusCode(); // Handle 100 and 101 responses internally by restarting the read again if ($statusCode == 100 || $statusCode == 101) { return $this->read(); } // Check headers to see what kind of connection / transfer encoding we have $headers = $responseObj->getHeaders(); /** * Responses to HEAD requests and 204 or 304 responses are not expected * to have a body - stop reading here */ if ($statusCode == 304 || $statusCode == 204 || $this->method == Request::METHOD_HEAD ) { // Close the connection if requested to do so by the server $connection = $headers->get('connection'); if ($connection && $connection->getFieldValue() == 'close') { $this->close(); } return $response; } // If we got a 'transfer-encoding: chunked' header $transferEncoding = $headers->get('transfer-encoding'); $contentLength = $headers->get('content-length'); if ($transferEncoding !== false) { if (strtolower($transferEncoding->getFieldValue()) == 'chunked') { do { $line = fgets($this->socket); $this->_checkSocketReadTimeout(); $chunk = $line; // Figure out the next chunk size $chunksize = trim($line); if (! ctype_xdigit($chunksize)) { $this->close(); throw new AdapterException\RuntimeException(sprintf( 'Invalid chunk size "%s" unable to read chunked body', $chunksize )); } // Convert the hexadecimal value to plain integer $chunksize = hexdec($chunksize); // Read next chunk $readTo = ftell($this->socket) + $chunksize; do { $currentPos = ftell($this->socket); if ($currentPos >= $readTo) { break; } if ($this->outStream) { if (stream_copy_to_stream($this->socket, $this->outStream, $readTo - $currentPos) == 0) { $this->_checkSocketReadTimeout(); break; } } else { $line = fread($this->socket, $readTo - $currentPos); if ($line === false || strlen($line) === 0) { $this->_checkSocketReadTimeout(); break; } $chunk .= $line; } } while (! feof($this->socket)); ErrorHandler::start(); $chunk .= fgets($this->socket); ErrorHandler::stop(); $this->_checkSocketReadTimeout(); if (! $this->outStream) { $response .= $chunk; } } while ($chunksize > 0); } else { $this->close(); throw new AdapterException\RuntimeException(sprintf( 'Cannot handle "%s" transfer encoding', $transferEncoding->getFieldValue() )); } // We automatically decode chunked-messages when writing to a stream // this means we have to disallow the Zend\Http\Response to do it again if ($this->outStream) { $response = str_ireplace("Transfer-Encoding: chunked\r\n", '', $response); } // Else, if we got the content-length header, read this number of bytes } elseif ($contentLength !== false) { // If we got more than one Content-Length header (see ZF-9404) use // the last value sent if (is_array($contentLength)) { $contentLength = $contentLength[count($contentLength) - 1]; } $contentLength = $contentLength->getFieldValue(); $currentPos = ftell($this->socket); for ($readTo = $currentPos + $contentLength; $readTo > $currentPos; $currentPos = ftell($this->socket)) { if ($this->outStream) { if (stream_copy_to_stream($this->socket, $this->outStream, $readTo - $currentPos) == 0) { $this->_checkSocketReadTimeout(); break; } } else { $chunk = fread($this->socket, $readTo - $currentPos); if ($chunk === false || strlen($chunk) === 0) { $this->_checkSocketReadTimeout(); break; } $response .= $chunk; } // Break if the connection ended prematurely if (feof($this->socket)) { break; } } // Fallback: just read the response until EOF } else { do { if ($this->outStream) { if (stream_copy_to_stream($this->socket, $this->outStream) == 0) { $this->_checkSocketReadTimeout(); break; } } else { $buff = fread($this->socket, 8192); if ($buff === false || strlen($buff) === 0) { $this->_checkSocketReadTimeout(); break; } else { $response .= $buff; } } } while (feof($this->socket) === false); $this->close(); } // Close the connection if requested to do so by the server $connection = $headers->get('connection'); if ($connection && $connection->getFieldValue() == 'close') { $this->close(); } return $response; } /** * Close the connection to the server * */ public function close() { if (is_resource($this->socket)) { ErrorHandler::start(); fclose($this->socket); ErrorHandler::stop(); } $this->socket = null; $this->connectedTo = [null, null]; } /** * Check if the socket has timed out - if so close connection and throw * an exception * * @throws AdapterException\TimeoutException with READ_TIMEOUT code */ // @codingStandardsIgnoreStart protected function _checkSocketReadTimeout() { // @codingStandardsIgnoreEnd if ($this->socket) { $info = stream_get_meta_data($this->socket); $timedout = $info['timed_out']; if ($timedout) { $this->close(); throw new AdapterException\TimeoutException( sprintf('Read timed out after %d seconds', $this->config['timeout']), AdapterException\TimeoutException::READ_TIMEOUT ); } } } /** * Set output stream for the response * * @param resource $stream * @return \Zend\Http\Client\Adapter\Socket */ public function setOutputStream($stream) { $this->outStream = $stream; return $this; } /** * Destructor: make sure the socket is disconnected * * If we are in persistent TCP mode, will not close the connection * */ public function __destruct() { if (! $this->config['persistent']) { if ($this->socket) { $this->close(); } } } }
php
BSD-3-Clause
ac4ffd09d509b2c5c0285178c4f7de740f05c3d9
2026-01-05T05:18:13.309357Z
false
zendframework/zend-http
https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/src/Client/Adapter/Curl.php
src/Client/Adapter/Curl.php
<?php /** * @see https://github.com/zendframework/zend-http for the canonical source repository * @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com) * @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License */ namespace Zend\Http\Client\Adapter; use Traversable; use Zend\Http\Client\Adapter\AdapterInterface as HttpAdapter; use Zend\Http\Client\Adapter\Exception as AdapterException; use Zend\Stdlib\ArrayUtils; /** * An adapter class for Zend\Http\Client based on the curl extension. * Curl requires libcurl. See for full requirements the PHP manual: http://php.net/curl */ class Curl implements HttpAdapter, StreamInterface { /** * Operation timeout. * * @var int */ const ERROR_OPERATION_TIMEDOUT = 28; /** * Parameters array * * @var array */ protected $config = []; /** * What host/port are we connected to? * * @var array */ protected $connectedTo = [null, null]; /** * The curl session handle * * @var resource|null */ protected $curl; /** * List of cURL options that should never be overwritten * * @var array */ protected $invalidOverwritableCurlOptions; /** * Response gotten from server * * @var string */ protected $response; /** * Stream for storing output * * @var resource */ protected $outputStream; /** * Adapter constructor * * Config is set using setOptions() * * @throws AdapterException\InitializationException */ public function __construct() { if (! extension_loaded('curl')) { throw new AdapterException\InitializationException( 'cURL extension has to be loaded to use this Zend\Http\Client adapter' ); } $this->invalidOverwritableCurlOptions = [ CURLOPT_HTTPGET, CURLOPT_POST, CURLOPT_UPLOAD, CURLOPT_CUSTOMREQUEST, CURLOPT_HEADER, CURLOPT_RETURNTRANSFER, CURLOPT_HTTPHEADER, CURLOPT_INFILE, CURLOPT_INFILESIZE, CURLOPT_PORT, CURLOPT_MAXREDIRS, CURLOPT_CONNECTTIMEOUT, ]; } /** * Set the configuration array for the adapter * * @param array|Traversable $options * @return $this * @throws AdapterException\InvalidArgumentException */ public function setOptions($options = []) { if ($options instanceof Traversable) { $options = ArrayUtils::iteratorToArray($options); } if (! is_array($options)) { throw new AdapterException\InvalidArgumentException(sprintf( 'Array or Traversable object expected, got %s', gettype($options) )); } /** Config Key Normalization */ foreach ($options as $k => $v) { unset($options[$k]); // unset original value $options[str_replace(['-', '_', ' ', '.'], '', strtolower($k))] = $v; // replace w/ normalized } if (isset($options['proxyuser']) && isset($options['proxypass'])) { $this->setCurlOption(CURLOPT_PROXYUSERPWD, $options['proxyuser'] . ':' . $options['proxypass']); unset($options['proxyuser'], $options['proxypass']); } if (isset($options['sslverifypeer'])) { $this->setCurlOption(CURLOPT_SSL_VERIFYPEER, $options['sslverifypeer']); unset($options['sslverifypeer']); } foreach ($options as $k => $v) { $option = strtolower($k); switch ($option) { case 'proxyhost': $this->setCurlOption(CURLOPT_PROXY, $v); break; case 'proxyport': $this->setCurlOption(CURLOPT_PROXYPORT, $v); break; default: if (is_array($v) && isset($this->config[$option]) && is_array($this->config[$option])) { $v = ArrayUtils::merge($this->config[$option], $v, true); } $this->config[$option] = $v; break; } } return $this; } /** * Retrieve the array of all configuration options * * @return array */ public function getConfig() { return $this->config; } /** * Direct setter for cURL adapter related options. * * @param string|int $option * @param mixed $value * @return $this */ public function setCurlOption($option, $value) { if (! isset($this->config['curloptions'])) { $this->config['curloptions'] = []; } $this->config['curloptions'][$option] = $value; return $this; } /** * Initialize curl * * @param string $host * @param int $port * @param bool $secure * @return void * @throws AdapterException\RuntimeException if unable to connect */ public function connect($host, $port = 80, $secure = false) { // If we're already connected, disconnect first if ($this->curl) { $this->close(); } // Do the actual connection $this->curl = curl_init(); if ($port != 80) { curl_setopt($this->curl, CURLOPT_PORT, intval($port)); } if (isset($this->config['connecttimeout'])) { $connectTimeout = $this->config['connecttimeout']; } elseif (isset($this->config['timeout'])) { $connectTimeout = $this->config['timeout']; } else { $connectTimeout = null; } if ($connectTimeout !== null && ! is_numeric($connectTimeout)) { throw new AdapterException\InvalidArgumentException(sprintf( 'integer or numeric string expected, got %s', gettype($connectTimeout) )); } if ($connectTimeout !== null) { $connectTimeout = (int) $connectTimeout; } if ($connectTimeout !== null) { if (defined('CURLOPT_CONNECTTIMEOUT_MS')) { curl_setopt($this->curl, CURLOPT_CONNECTTIMEOUT_MS, $connectTimeout * 1000); } else { curl_setopt($this->curl, CURLOPT_CONNECTTIMEOUT, $connectTimeout); } } if (isset($this->config['timeout'])) { if (defined('CURLOPT_TIMEOUT_MS')) { curl_setopt($this->curl, CURLOPT_TIMEOUT_MS, $this->config['timeout'] * 1000); } else { curl_setopt($this->curl, CURLOPT_TIMEOUT, $this->config['timeout']); } } if (isset($this->config['sslcafile']) && $this->config['sslcafile']) { curl_setopt($this->curl, CURLOPT_CAINFO, $this->config['sslcafile']); } if (isset($this->config['sslcapath']) && $this->config['sslcapath']) { curl_setopt($this->curl, CURLOPT_CAPATH, $this->config['sslcapath']); } if (isset($this->config['maxredirects'])) { // Set Max redirects curl_setopt($this->curl, CURLOPT_MAXREDIRS, $this->config['maxredirects']); } if (! $this->curl) { $this->close(); throw new AdapterException\RuntimeException('Unable to Connect to ' . $host . ':' . $port); } if ($secure !== false) { // Behave the same like Zend\Http\Adapter\Socket on SSL options. if (isset($this->config['sslcert'])) { curl_setopt($this->curl, CURLOPT_SSLCERT, $this->config['sslcert']); } if (isset($this->config['sslpassphrase'])) { curl_setopt($this->curl, CURLOPT_SSLCERTPASSWD, $this->config['sslpassphrase']); } } // Update connected_to $this->connectedTo = [$host, $port]; } /** * Send request to the remote server * * @param string $method * @param \Zend\Uri\Uri $uri * @param float $httpVersion * @param array $headers * @param string $body * @return string $request * @throws AdapterException\RuntimeException If connection fails, connected * to wrong host, no PUT file defined, unsupported method, or unsupported * cURL option. * @throws AdapterException\InvalidArgumentException if $method is currently not supported * @throws AdapterException\TimeoutException if connection timed out */ public function write($method, $uri, $httpVersion = 1.1, $headers = [], $body = '') { // Make sure we're properly connected if (! $this->curl) { throw new AdapterException\RuntimeException('Trying to write but we are not connected'); } if ($this->connectedTo[0] != $uri->getHost() || $this->connectedTo[1] != $uri->getPort()) { throw new AdapterException\RuntimeException('Trying to write but we are connected to the wrong host'); } // set URL curl_setopt($this->curl, CURLOPT_URL, $uri->__toString()); // ensure correct curl call $curlValue = true; switch ($method) { case 'GET': $curlMethod = CURLOPT_HTTPGET; break; case 'POST': $curlMethod = CURLOPT_POST; break; case 'PUT': // There are two different types of PUT request, either a Raw Data string has been set // or CURLOPT_INFILE and CURLOPT_INFILESIZE are used. if (is_resource($body)) { $this->config['curloptions'][CURLOPT_INFILE] = $body; } if (isset($this->config['curloptions'][CURLOPT_INFILE])) { // Now we will probably already have Content-Length set, so that we have to delete it // from $headers at this point: if (! isset($headers['Content-Length']) && ! isset($this->config['curloptions'][CURLOPT_INFILESIZE]) ) { throw new AdapterException\RuntimeException( 'Cannot set a file-handle for cURL option CURLOPT_INFILE' . ' without also setting its size in CURLOPT_INFILESIZE.' ); } if (isset($headers['Content-Length'])) { $this->config['curloptions'][CURLOPT_INFILESIZE] = (int) $headers['Content-Length']; unset($headers['Content-Length']); } if (is_resource($body)) { $body = ''; } $curlMethod = CURLOPT_UPLOAD; } else { $curlMethod = CURLOPT_CUSTOMREQUEST; $curlValue = 'PUT'; } break; case 'PATCH': $curlMethod = CURLOPT_CUSTOMREQUEST; $curlValue = 'PATCH'; break; case 'DELETE': $curlMethod = CURLOPT_CUSTOMREQUEST; $curlValue = 'DELETE'; break; case 'OPTIONS': $curlMethod = CURLOPT_CUSTOMREQUEST; $curlValue = 'OPTIONS'; break; case 'TRACE': $curlMethod = CURLOPT_CUSTOMREQUEST; $curlValue = 'TRACE'; break; case 'HEAD': $curlMethod = CURLOPT_CUSTOMREQUEST; $curlValue = 'HEAD'; break; default: // For now, through an exception for unsupported request methods throw new AdapterException\InvalidArgumentException(sprintf( 'Method \'%s\' currently not supported', $method )); } if (is_resource($body) && $curlMethod != CURLOPT_UPLOAD) { throw new AdapterException\RuntimeException('Streaming requests are allowed only with PUT'); } // get http version to use $curlHttp = $httpVersion == 1.1 ? CURL_HTTP_VERSION_1_1 : CURL_HTTP_VERSION_1_0; // mark as HTTP request and set HTTP method curl_setopt($this->curl, CURLOPT_HTTP_VERSION, $curlHttp); curl_setopt($this->curl, $curlMethod, $curlValue); // Set the CURLINFO_HEADER_OUT flag so that we can retrieve the full request string later curl_setopt($this->curl, CURLINFO_HEADER_OUT, true); if ($this->outputStream) { // headers will be read into the response curl_setopt($this->curl, CURLOPT_HEADER, false); curl_setopt($this->curl, CURLOPT_HEADERFUNCTION, [$this, 'readHeader']); // and data will be written into the file curl_setopt($this->curl, CURLOPT_FILE, $this->outputStream); } else { // ensure headers are also returned curl_setopt($this->curl, CURLOPT_HEADER, true); // ensure actual response is returned curl_setopt($this->curl, CURLOPT_RETURNTRANSFER, true); } // Treating basic auth headers in a special way if (array_key_exists('Authorization', $headers) && 'Basic' == substr($headers['Authorization'], 0, 5)) { curl_setopt($this->curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC); curl_setopt($this->curl, CURLOPT_USERPWD, base64_decode(substr($headers['Authorization'], 6))); unset($headers['Authorization']); } // set additional headers if (! isset($headers['Accept'])) { $headers['Accept'] = ''; } $curlHeaders = []; foreach ($headers as $key => $value) { $curlHeaders[] = $key . ': ' . $value; } curl_setopt($this->curl, CURLOPT_HTTPHEADER, $curlHeaders); /** * Make sure POSTFIELDS is set after $curlMethod is set: * @link http://de2.php.net/manual/en/function.curl-setopt.php#81161 */ if ($curlMethod == CURLOPT_UPLOAD) { // this covers a PUT by file-handle: // Make the setting of this options explicit (rather than setting it through the loop following a bit lower) // to group common functionality together. curl_setopt($this->curl, CURLOPT_INFILE, $this->config['curloptions'][CURLOPT_INFILE]); curl_setopt($this->curl, CURLOPT_INFILESIZE, $this->config['curloptions'][CURLOPT_INFILESIZE]); unset($this->config['curloptions'][CURLOPT_INFILE]); unset($this->config['curloptions'][CURLOPT_INFILESIZE]); } elseif (in_array($method, ['POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'], true)) { curl_setopt($this->curl, CURLOPT_POSTFIELDS, $body); } // set additional curl options if (isset($this->config['curloptions'])) { foreach ((array) $this->config['curloptions'] as $k => $v) { if (! in_array($k, $this->invalidOverwritableCurlOptions)) { if (curl_setopt($this->curl, $k, $v) == false) { throw new AdapterException\RuntimeException(sprintf( 'Unknown or erroreous cURL option "%s" set', $k )); } } } } $this->response = ''; // send the request $response = curl_exec($this->curl); // if we used streaming, headers are already there if (! is_resource($this->outputStream)) { $this->response = $response; } $request = curl_getinfo($this->curl, CURLINFO_HEADER_OUT); $request .= $body; if ($response === false || empty($this->response)) { if (curl_errno($this->curl) === static::ERROR_OPERATION_TIMEDOUT) { throw new AdapterException\TimeoutException( 'Read timed out', AdapterException\TimeoutException::READ_TIMEOUT ); } throw new AdapterException\RuntimeException(sprintf( 'Error in cURL request: %s', curl_error($this->curl) )); } // separating header from body because it is dangerous to accidentially replace strings in the body $responseHeaderSize = curl_getinfo($this->curl, CURLINFO_HEADER_SIZE); $responseHeaders = substr($this->response, 0, $responseHeaderSize); // cURL automatically decodes chunked-messages, this means we have to // disallow the Zend\Http\Response to do it again. $responseHeaders = preg_replace("/Transfer-Encoding:\s*chunked\\r\\n/i", '', $responseHeaders); // cURL can automatically handle content encoding; prevent double-decoding from occurring if (isset($this->config['curloptions'][CURLOPT_ENCODING]) && '' == $this->config['curloptions'][CURLOPT_ENCODING] ) { $responseHeaders = preg_replace("/Content-Encoding:\s*gzip\\r\\n/i", '', $responseHeaders); } // cURL automatically handles Proxy rewrites, remove the "HTTP/1.0 200 Connection established" string: $responseHeaders = preg_replace( "/HTTP\/1.[01]\s*200\s*Connection\s*established\\r\\n\\r\\n/", '', $responseHeaders ); // replace old header with new, cleaned up, header $this->response = substr_replace($this->response, $responseHeaders, 0, $responseHeaderSize); // Eliminate multiple HTTP responses. do { $parts = preg_split('|(?:\r?\n){2}|m', $this->response, 2); $again = false; if (isset($parts[1]) && preg_match("|^HTTP/1\.[01](.*?)\r\n|mi", $parts[1])) { $this->response = $parts[1]; $again = true; } } while ($again); return $request; } /** * Return read response from server * * @return string */ public function read() { return $this->response; } /** * Close the connection to the server * */ public function close() { if (is_resource($this->curl)) { curl_close($this->curl); } $this->curl = null; $this->connectedTo = [null, null]; } /** * Get cUrl Handle * * @return resource */ public function getHandle() { return $this->curl; } /** * Set output stream for the response * * @param resource $stream * @return $this */ public function setOutputStream($stream) { $this->outputStream = $stream; return $this; } /** * Header reader function for CURL * * @param resource $curl * @param string $header * @return int */ public function readHeader($curl, $header) { $this->response .= $header; return strlen($header); } }
php
BSD-3-Clause
ac4ffd09d509b2c5c0285178c4f7de740f05c3d9
2026-01-05T05:18:13.309357Z
false
zendframework/zend-http
https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/src/Client/Adapter/Test.php
src/Client/Adapter/Test.php
<?php /** * @see https://github.com/zendframework/zend-http for the canonical source repository * @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com) * @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License */ namespace Zend\Http\Client\Adapter; use Traversable; use Zend\Http\Response; use Zend\Stdlib\ArrayUtils; /** * A testing-purposes adapter. * * Should be used to test all components that rely on Zend\Http\Client, * without actually performing an HTTP request. You should instantiate this * object manually, and then set it as the client's adapter. Then, you can * set the expected response using the setResponse() method. */ class Test implements AdapterInterface { /** * Parameters array * * @var array */ protected $config = []; /** * Buffer of responses to be returned by the read() method. Can be * set using setResponse() and addResponse(). * * @var array */ protected $responses = ["HTTP/1.1 400 Bad Request\r\n\r\n"]; /** * Current position in the response buffer * * @var int */ protected $responseIndex = 0; /** * Whether or not the next request will fail with an exception * * @var bool */ protected $nextRequestWillFail = false; /** * Adapter constructor, currently empty. Config is set using setOptions() */ public function __construct() { } /** * Set the nextRequestWillFail flag * * @param bool $flag * @return \Zend\Http\Client\Adapter\Test */ public function setNextRequestWillFail($flag) { $this->nextRequestWillFail = (bool) $flag; return $this; } /** * Set the configuration array for the adapter * * @param array|Traversable $options * @throws Exception\InvalidArgumentException */ public function setOptions($options = []) { if ($options instanceof Traversable) { $options = ArrayUtils::iteratorToArray($options); } if (! is_array($options)) { throw new Exception\InvalidArgumentException( 'Array or Traversable object expected, got ' . gettype($options) ); } foreach ($options as $k => $v) { $this->config[strtolower($k)] = $v; } } /** * Connect to the remote server * * @param string $host * @param int $port * @param bool $secure * @throws Exception\RuntimeException */ public function connect($host, $port = 80, $secure = false) { if ($this->nextRequestWillFail) { $this->nextRequestWillFail = false; throw new Exception\RuntimeException('Request failed'); } } /** * Send request to the remote server * * @param string $method * @param \Zend\Uri\Uri $uri * @param string $httpVer * @param array $headers * @param string $body * @return string Request as string */ public function write($method, $uri, $httpVer = '1.1', $headers = [], $body = '') { // Build request headers $path = $uri->getPath(); if (empty($path)) { $path = '/'; } $query = $uri->getQuery(); $path .= $query ? '?' . $query : ''; $request = $method . ' ' . $path . ' HTTP/' . $httpVer . "\r\n"; foreach ($headers as $k => $v) { if (is_string($k)) { $v = $k . ': ' . $v; } $request .= $v . "\r\n"; } // Add the request body $request .= "\r\n" . $body; // Do nothing - just return the request as string return $request; } /** * Return the response set in $this->setResponse() * * @return string */ public function read() { if ($this->responseIndex >= count($this->responses)) { $this->responseIndex = 0; } return $this->responses[$this->responseIndex++]; } /** * Close the connection (dummy) * */ public function close() { } /** * Set the HTTP response(s) to be returned by this adapter * * @param \Zend\Http\Response|array|string $response */ public function setResponse($response) { if ($response instanceof Response) { $response = $response->toString(); } $this->responses = (array) $response; $this->responseIndex = 0; } /** * Add another response to the response buffer. * * @param string|Response $response */ public function addResponse($response) { if ($response instanceof Response) { $response = $response->toString(); } $this->responses[] = $response; } /** * Sets the position of the response buffer. Selects which * response will be returned on the next call to read(). * * @param int $index * @throws Exception\OutOfRangeException */ public function setResponseIndex($index) { if ($index < 0 || $index >= count($this->responses)) { throw new Exception\OutOfRangeException( 'Index out of range of response buffer size' ); } $this->responseIndex = $index; } }
php
BSD-3-Clause
ac4ffd09d509b2c5c0285178c4f7de740f05c3d9
2026-01-05T05:18:13.309357Z
false
zendframework/zend-http
https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/src/Client/Adapter/AdapterInterface.php
src/Client/Adapter/AdapterInterface.php
<?php /** * @see https://github.com/zendframework/zend-http for the canonical source repository * @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com) * @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License */ namespace Zend\Http\Client\Adapter; /** * An interface description for Zend\Http\Client\Adapter classes. * * These classes are used as connectors for Zend\Http\Client, performing the * tasks of connecting, writing, reading and closing connection to the server. */ interface AdapterInterface { /** * Set the configuration array for the adapter * * @param array $options */ public function setOptions($options = []); /** * Connect to the remote server * * @param string $host * @param int $port * @param bool $secure */ public function connect($host, $port = 80, $secure = false); /** * Send request to the remote server * * @param string $method * @param \Zend\Uri\Uri $url * @param string $httpVer * @param array $headers * @param string $body * @return string Request as text */ public function write($method, $url, $httpVer = '1.1', $headers = [], $body = ''); /** * Read response from server * * @return string */ public function read(); /** * Close the connection to the server * */ public function close(); }
php
BSD-3-Clause
ac4ffd09d509b2c5c0285178c4f7de740f05c3d9
2026-01-05T05:18:13.309357Z
false
zendframework/zend-http
https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/src/Client/Adapter/StreamInterface.php
src/Client/Adapter/StreamInterface.php
<?php /** * @see https://github.com/zendframework/zend-http for the canonical source repository * @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com) * @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License */ namespace Zend\Http\Client\Adapter; /** * An interface description for Zend\Http\Client\Adapter\Stream classes. * * This interface describes Zend\Http\Client\Adapter which supports streaming. */ interface StreamInterface { /** * Set output stream * * This function sets output stream where the result will be stored. * * @param resource $stream Stream to write the output to * */ public function setOutputStream($stream); }
php
BSD-3-Clause
ac4ffd09d509b2c5c0285178c4f7de740f05c3d9
2026-01-05T05:18:13.309357Z
false
zendframework/zend-http
https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/src/Client/Adapter/Exception/OutOfRangeException.php
src/Client/Adapter/Exception/OutOfRangeException.php
<?php /** * @see https://github.com/zendframework/zend-http for the canonical source repository * @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com) * @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License */ namespace Zend\Http\Client\Adapter\Exception; use Zend\Http\Client\Exception; class OutOfRangeException extends Exception\OutOfRangeException implements ExceptionInterface { }
php
BSD-3-Clause
ac4ffd09d509b2c5c0285178c4f7de740f05c3d9
2026-01-05T05:18:13.309357Z
false
zendframework/zend-http
https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/src/Client/Adapter/Exception/ExceptionInterface.php
src/Client/Adapter/Exception/ExceptionInterface.php
<?php /** * @see https://github.com/zendframework/zend-http for the canonical source repository * @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com) * @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License */ namespace Zend\Http\Client\Adapter\Exception; use Zend\Http\Client\Exception\ExceptionInterface as HttpClientException; interface ExceptionInterface extends HttpClientException { }
php
BSD-3-Clause
ac4ffd09d509b2c5c0285178c4f7de740f05c3d9
2026-01-05T05:18:13.309357Z
false
zendframework/zend-http
https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/src/Client/Adapter/Exception/RuntimeException.php
src/Client/Adapter/Exception/RuntimeException.php
<?php /** * @see https://github.com/zendframework/zend-http for the canonical source repository * @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com) * @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License */ namespace Zend\Http\Client\Adapter\Exception; use Zend\Http\Client\Exception; class RuntimeException extends Exception\RuntimeException implements ExceptionInterface { }
php
BSD-3-Clause
ac4ffd09d509b2c5c0285178c4f7de740f05c3d9
2026-01-05T05:18:13.309357Z
false
zendframework/zend-http
https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/src/Client/Adapter/Exception/TimeoutException.php
src/Client/Adapter/Exception/TimeoutException.php
<?php /** * @see https://github.com/zendframework/zend-http for the canonical source repository * @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com) * @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License */ namespace Zend\Http\Client\Adapter\Exception; class TimeoutException extends RuntimeException implements ExceptionInterface { const READ_TIMEOUT = 1000; }
php
BSD-3-Clause
ac4ffd09d509b2c5c0285178c4f7de740f05c3d9
2026-01-05T05:18:13.309357Z
false
zendframework/zend-http
https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/src/Client/Adapter/Exception/InvalidArgumentException.php
src/Client/Adapter/Exception/InvalidArgumentException.php
<?php /** * @see https://github.com/zendframework/zend-http for the canonical source repository * @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com) * @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License */ namespace Zend\Http\Client\Adapter\Exception; use Zend\Http\Client\Exception; class InvalidArgumentException extends Exception\InvalidArgumentException implements ExceptionInterface { }
php
BSD-3-Clause
ac4ffd09d509b2c5c0285178c4f7de740f05c3d9
2026-01-05T05:18:13.309357Z
false
zendframework/zend-http
https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/src/Client/Adapter/Exception/InitializationException.php
src/Client/Adapter/Exception/InitializationException.php
<?php /** * @see https://github.com/zendframework/zend-http for the canonical source repository * @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com) * @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License */ namespace Zend\Http\Client\Adapter\Exception; class InitializationException extends RuntimeException { }
php
BSD-3-Clause
ac4ffd09d509b2c5c0285178c4f7de740f05c3d9
2026-01-05T05:18:13.309357Z
false
zendframework/zend-http
https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/src/Response/Stream.php
src/Response/Stream.php
<?php /** * @see https://github.com/zendframework/zend-http for the canonical source repository * @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com) * @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License */ namespace Zend\Http\Response; use Zend\Http\Exception; use Zend\Http\Response; use Zend\Stdlib\ErrorHandler; /** * Represents an HTTP response message as PHP stream resource */ class Stream extends Response { /** * The Content-Length value, if set * * @var int */ protected $contentLength; /** * The portion of the body that has already been streamed * * @var int */ protected $contentStreamed = 0; /** * Response as stream * * @var resource */ protected $stream; /** * The name of the file containing the stream * * Will be empty if stream is not file-based. * * @var string */ protected $streamName; /** * Should we clean up the stream file when this response is closed? * * @var bool */ protected $cleanup; /** * Set content length * * @param int $contentLength */ public function setContentLength($contentLength = null) { $this->contentLength = $contentLength; } /** * Get content length * * @return int|null */ public function getContentLength() { return $this->contentLength; } /** * Get the response as stream * * @return resource */ public function getStream() { return $this->stream; } /** * Set the response stream * * @param resource $stream * @return $this */ public function setStream($stream) { $this->stream = $stream; return $this; } /** * Get the cleanup trigger * * @return bool */ public function getCleanup() { return $this->cleanup; } /** * Set the cleanup trigger * * @param bool $cleanup */ public function setCleanup($cleanup = true) { $this->cleanup = $cleanup; } /** * Get file name associated with the stream * * @return string */ public function getStreamName() { return $this->streamName; } /** * Set file name associated with the stream * * @param string $streamName Name to set * @return $this */ public function setStreamName($streamName) { $this->streamName = $streamName; return $this; } /** * Create a new Zend\Http\Response\Stream object from a stream * * @param string $responseString * @param resource $stream * @return $this * @throws Exception\InvalidArgumentException * @throws Exception\OutOfRangeException */ public static function fromStream($responseString, $stream) { if (! is_resource($stream) || get_resource_type($stream) !== 'stream') { throw new Exception\InvalidArgumentException('A valid stream is required'); } $headerComplete = false; $headersString = ''; $responseArray = []; if ($responseString) { $responseArray = explode("\n", $responseString); } while (! empty($responseArray)) { $nextLine = array_shift($responseArray); $headersString .= $nextLine . "\n"; $nextLineTrimmed = trim($nextLine); if ($nextLineTrimmed == '') { $headerComplete = true; break; } } if (! $headerComplete) { while (false !== ($nextLine = fgets($stream))) { $headersString .= trim($nextLine) . "\r\n"; if ($nextLine == "\r\n" || $nextLine == "\n") { $headerComplete = true; break; } } } if (! $headerComplete) { throw new Exception\OutOfRangeException('End of header not found'); } /** @var Stream $response */ $response = static::fromString($headersString); if (is_resource($stream)) { $response->setStream($stream); } if (! empty($responseArray)) { $response->content = implode("\n", $responseArray); } $headers = $response->getHeaders(); foreach ($headers as $header) { if ($header instanceof \Zend\Http\Header\ContentLength) { $response->setContentLength((int) $header->getFieldValue()); $contentLength = $response->getContentLength(); if (strlen($response->content) > $contentLength) { throw new Exception\OutOfRangeException(sprintf( 'Too much content was extracted from the stream (%d instead of %d bytes)', strlen($response->content), $contentLength )); } break; } } return $response; } /** * Get the response body as string * * This method returns the body of the HTTP response (the content), as it * should be in it's readable version - that is, after decoding it (if it * was decoded), deflating it (if it was gzip compressed), etc. * * If you want to get the raw body (as transferred on wire) use * $this->getRawBody() instead. * * @return string */ public function getBody() { if ($this->stream !== null) { $this->readStream(); } return parent::getBody(); } /** * Get the raw response body (as transferred "on wire") as string * * If the body is encoded (with Transfer-Encoding, not content-encoding - * IE "chunked" body), gzip compressed, etc. it will not be decoded. * * @return string */ public function getRawBody() { if ($this->stream) { $this->readStream(); } return $this->content; } /** * Read stream content and return it as string * * Function reads the remainder of the body from the stream and closes the stream. * * @return string */ protected function readStream() { $contentLength = $this->getContentLength(); if (null !== $contentLength) { $bytes = $contentLength - $this->contentStreamed; } else { $bytes = -1; // Read the whole buffer } if (! is_resource($this->stream) || $bytes == 0) { return ''; } $this->content .= stream_get_contents($this->stream, $bytes); $this->contentStreamed += strlen($this->content); if ($this->getContentLength() == $this->contentStreamed) { $this->stream = null; } } /** * Destructor */ public function __destruct() { if (is_resource($this->stream)) { $this->stream = null; //Could be listened by others } if ($this->cleanup) { ErrorHandler::start(E_WARNING); unlink($this->streamName); ErrorHandler::stop(); } } }
php
BSD-3-Clause
ac4ffd09d509b2c5c0285178c4f7de740f05c3d9
2026-01-05T05:18:13.309357Z
false
zendframework/zend-http
https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/src/Exception/OutOfRangeException.php
src/Exception/OutOfRangeException.php
<?php /** * @see https://github.com/zendframework/zend-http for the canonical source repository * @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com) * @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License */ namespace Zend\Http\Exception; class OutOfRangeException extends \OutOfRangeException implements ExceptionInterface { }
php
BSD-3-Clause
ac4ffd09d509b2c5c0285178c4f7de740f05c3d9
2026-01-05T05:18:13.309357Z
false
zendframework/zend-http
https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/src/Exception/ExceptionInterface.php
src/Exception/ExceptionInterface.php
<?php /** * @see https://github.com/zendframework/zend-http for the canonical source repository * @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com) * @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License */ namespace Zend\Http\Exception; interface ExceptionInterface { }
php
BSD-3-Clause
ac4ffd09d509b2c5c0285178c4f7de740f05c3d9
2026-01-05T05:18:13.309357Z
false
zendframework/zend-http
https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/src/Exception/RuntimeException.php
src/Exception/RuntimeException.php
<?php /** * @see https://github.com/zendframework/zend-http for the canonical source repository * @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com) * @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License */ namespace Zend\Http\Exception; class RuntimeException extends \RuntimeException implements ExceptionInterface { }
php
BSD-3-Clause
ac4ffd09d509b2c5c0285178c4f7de740f05c3d9
2026-01-05T05:18:13.309357Z
false
zendframework/zend-http
https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/src/Exception/InvalidArgumentException.php
src/Exception/InvalidArgumentException.php
<?php /** * @see https://github.com/zendframework/zend-http for the canonical source repository * @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com) * @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License */ namespace Zend\Http\Exception; class InvalidArgumentException extends \InvalidArgumentException implements ExceptionInterface { }
php
BSD-3-Clause
ac4ffd09d509b2c5c0285178c4f7de740f05c3d9
2026-01-05T05:18:13.309357Z
false
zendframework/zend-http
https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/src/PhpEnvironment/RemoteAddress.php
src/PhpEnvironment/RemoteAddress.php
<?php /** * @see https://github.com/zendframework/zend-http for the canonical source repository * @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com) * @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License */ namespace Zend\Http\PhpEnvironment; /** * Functionality for determining client IP address. */ class RemoteAddress { /** * Whether to use proxy addresses or not. * * As default this setting is disabled - IP address is mostly needed to increase * security. HTTP_* are not reliable since can easily be spoofed. It can be enabled * just for more flexibility, but if user uses proxy to connect to trusted services * it's his/her own risk, only reliable field for IP address is $_SERVER['REMOTE_ADDR']. * * @var bool */ protected $useProxy = false; /** * List of trusted proxy IP addresses * * @var array */ protected $trustedProxies = []; /** * HTTP header to introspect for proxies * * @var string */ protected $proxyHeader = 'HTTP_X_FORWARDED_FOR'; /** * Changes proxy handling setting. * * This must be static method, since validators are recovered automatically * at session read, so this is the only way to switch setting. * * @param bool $useProxy Whether to check also proxied IP addresses. * @return $this */ public function setUseProxy($useProxy = true) { $this->useProxy = $useProxy; return $this; } /** * Checks proxy handling setting. * * @return bool Current setting value. */ public function getUseProxy() { return $this->useProxy; } /** * Set list of trusted proxy addresses * * @param array $trustedProxies * @return $this */ public function setTrustedProxies(array $trustedProxies) { $this->trustedProxies = $trustedProxies; return $this; } /** * Set the header to introspect for proxy IPs * * @param string $header * @return $this */ public function setProxyHeader($header = 'X-Forwarded-For') { $this->proxyHeader = $this->normalizeProxyHeader($header); return $this; } /** * Returns client IP address. * * @return string IP address. */ public function getIpAddress() { $ip = $this->getIpAddressFromProxy(); if ($ip) { return $ip; } // direct IP address if (isset($_SERVER['REMOTE_ADDR'])) { return $_SERVER['REMOTE_ADDR']; } return ''; } /** * Attempt to get the IP address for a proxied client * * @see http://tools.ietf.org/html/draft-ietf-appsawg-http-forwarded-10#section-5.2 * @return false|string */ protected function getIpAddressFromProxy() { if (! $this->useProxy || (isset($_SERVER['REMOTE_ADDR']) && ! in_array($_SERVER['REMOTE_ADDR'], $this->trustedProxies)) ) { return false; } $header = $this->proxyHeader; if (! isset($_SERVER[$header]) || empty($_SERVER[$header])) { return false; } // Extract IPs $ips = explode(',', $_SERVER[$header]); // trim, so we can compare against trusted proxies properly $ips = array_map('trim', $ips); // remove trusted proxy IPs $ips = array_diff($ips, $this->trustedProxies); // Any left? if (empty($ips)) { return false; } // Since we've removed any known, trusted proxy servers, the right-most // address represents the first IP we do not know about -- i.e., we do // not know if it is a proxy server, or a client. As such, we treat it // as the originating IP. // @see http://en.wikipedia.org/wiki/X-Forwarded-For $ip = array_pop($ips); return $ip; } /** * Normalize a header string * * Normalizes a header string to a format that is compatible with * $_SERVER * * @param string $header * @return string */ protected function normalizeProxyHeader($header) { $header = strtoupper($header); $header = str_replace('-', '_', $header); if (0 !== strpos($header, 'HTTP_')) { $header = 'HTTP_' . $header; } return $header; } }
php
BSD-3-Clause
ac4ffd09d509b2c5c0285178c4f7de740f05c3d9
2026-01-05T05:18:13.309357Z
false
zendframework/zend-http
https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/src/PhpEnvironment/Request.php
src/PhpEnvironment/Request.php
<?php /** * @see https://github.com/zendframework/zend-http for the canonical source repository * @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com) * @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License */ namespace Zend\Http\PhpEnvironment; use Zend\Http\Header\Cookie; use Zend\Http\Request as HttpRequest; use Zend\Stdlib\Parameters; use Zend\Stdlib\ParametersInterface; use Zend\Uri\Http as HttpUri; use Zend\Validator\Hostname as HostnameValidator; /** * HTTP Request for current PHP environment */ class Request extends HttpRequest { /** * Base URL of the application. * * @var string */ protected $baseUrl; /** * Base Path of the application. * * @var string */ protected $basePath; /** * Actual request URI, independent of the platform. * * @var string */ protected $requestUri; /** * PHP server params ($_SERVER) * * @var ParametersInterface */ protected $serverParams; /** * PHP environment params ($_ENV) * * @var ParametersInterface */ protected $envParams; /** * Construct * Instantiates request. * * @param bool $allowCustomMethods */ public function __construct($allowCustomMethods = true) { $this->setAllowCustomMethods($allowCustomMethods); $this->setEnv(new Parameters($_ENV)); if ($_GET) { $this->setQuery(new Parameters($_GET)); } if ($_POST) { $this->setPost(new Parameters($_POST)); } if ($_COOKIE) { $this->setCookies(new Parameters($_COOKIE)); } if ($_FILES) { // convert PHP $_FILES superglobal $files = $this->mapPhpFiles(); $this->setFiles(new Parameters($files)); } $this->setServer(new Parameters($_SERVER)); } /** * Get raw request body * * @return string */ public function getContent() { if (empty($this->content)) { $requestBody = file_get_contents('php://input'); if (strlen($requestBody) > 0) { $this->content = $requestBody; } } return $this->content; } /** * Set cookies * * Instantiate and set cookies. * * @param $cookie * @return $this */ public function setCookies($cookie) { $this->getHeaders()->addHeader(new Cookie((array) $cookie)); return $this; } /** * Set the request URI. * * @param string $requestUri * @return $this */ public function setRequestUri($requestUri) { $this->requestUri = $requestUri; return $this; } /** * Get the request URI. * * @return string */ public function getRequestUri() { if ($this->requestUri === null) { $this->requestUri = $this->detectRequestUri(); } return $this->requestUri; } /** * Set the base URL. * * @param string $baseUrl * @return $this */ public function setBaseUrl($baseUrl) { $this->baseUrl = rtrim($baseUrl, '/'); return $this; } /** * Get the base URL. * * @return string */ public function getBaseUrl() { if ($this->baseUrl === null) { $this->setBaseUrl($this->detectBaseUrl()); } return $this->baseUrl; } /** * Set the base path. * * @param string $basePath * @return $this */ public function setBasePath($basePath) { $this->basePath = rtrim($basePath, '/'); return $this; } /** * Get the base path. * * @return string */ public function getBasePath() { if ($this->basePath === null) { $this->setBasePath($this->detectBasePath()); } return $this->basePath; } /** * Provide an alternate Parameter Container implementation for server parameters in this object, * (this is NOT the primary API for value setting, for that see getServer()) * * @param ParametersInterface $server * @return $this */ public function setServer(ParametersInterface $server) { $this->serverParams = $server; // This seems to be the only way to get the Authorization header on Apache if (function_exists('apache_request_headers')) { $apacheRequestHeaders = apache_request_headers(); if (! isset($this->serverParams['HTTP_AUTHORIZATION'])) { if (isset($apacheRequestHeaders['Authorization'])) { $this->serverParams->set('HTTP_AUTHORIZATION', $apacheRequestHeaders['Authorization']); } elseif (isset($apacheRequestHeaders['authorization'])) { $this->serverParams->set('HTTP_AUTHORIZATION', $apacheRequestHeaders['authorization']); } } } // set headers $headers = []; foreach ($server as $key => $value) { if ($value || (! is_array($value) && strlen($value))) { if (strpos($key, 'HTTP_') === 0) { if (strpos($key, 'HTTP_COOKIE') === 0) { // Cookies are handled using the $_COOKIE superglobal continue; } $headers[strtr(ucwords(strtolower(strtr(substr($key, 5), '_', ' '))), ' ', '-')] = $value; } elseif (strpos($key, 'CONTENT_') === 0) { $name = substr($key, 8); // Remove "Content-" $headers['Content-' . (($name == 'MD5') ? $name : ucfirst(strtolower($name)))] = $value; } } } $this->getHeaders()->addHeaders($headers); // set method if (isset($this->serverParams['REQUEST_METHOD'])) { $this->setMethod($this->serverParams['REQUEST_METHOD']); } // set HTTP version if (isset($this->serverParams['SERVER_PROTOCOL']) && strpos($this->serverParams['SERVER_PROTOCOL'], self::VERSION_10) !== false ) { $this->setVersion(self::VERSION_10); } // set URI $uri = new HttpUri(); // URI scheme if ((! empty($this->serverParams['HTTPS']) && strtolower($this->serverParams['HTTPS']) !== 'off') || (! empty($this->serverParams['HTTP_X_FORWARDED_PROTO']) && $this->serverParams['HTTP_X_FORWARDED_PROTO'] == 'https') ) { $scheme = 'https'; } else { $scheme = 'http'; } $uri->setScheme($scheme); // URI host & port $host = null; $port = null; // Set the host $headerHost = $this->getHeaders()->get('host'); if ($headerHost) { $host = $headerHost->getFieldValue(); // works for regname, IPv4 & IPv6 if (preg_match('|\:(\d+)$|', $host, $matches)) { $host = substr($host, 0, -1 * (strlen($matches[1]) + 1)); $port = (int) $matches[1]; } // set up a validator that check if the hostname is legal (not spoofed) $hostnameValidator = new HostnameValidator([ 'allow' => HostnameValidator::ALLOW_ALL, 'useIdnCheck' => false, 'useTldCheck' => false, ]); // If invalid. Reset the host & port if (! $hostnameValidator->isValid($host)) { $host = null; $port = null; } } if (! $host && isset($this->serverParams['SERVER_NAME'])) { $host = $this->serverParams['SERVER_NAME']; if (isset($this->serverParams['SERVER_PORT'])) { $port = (int) $this->serverParams['SERVER_PORT']; } // Check for missinterpreted IPv6-Address // Reported at least for Safari on Windows if (isset($this->serverParams['SERVER_ADDR']) && preg_match('/^\[[0-9a-fA-F\:]+\]$/', $host)) { $host = '[' . $this->serverParams['SERVER_ADDR'] . ']'; if ($port . ']' == substr($host, strrpos($host, ':') + 1)) { // The last digit of the IPv6-Address has been taken as port // Unset the port so the default port can be used $port = null; } } } $uri->setHost($host); $uri->setPort($port); // URI path $requestUri = $this->getRequestUri(); if (($qpos = strpos($requestUri, '?')) !== false) { $requestUri = substr($requestUri, 0, $qpos); } $uri->setPath($requestUri); // URI query if (isset($this->serverParams['QUERY_STRING'])) { $uri->setQuery($this->serverParams['QUERY_STRING']); } $this->setUri($uri); return $this; } /** * Return the parameter container responsible for server parameters or a single parameter value. * * @param string|null $name Parameter name to retrieve, or null to get the whole container. * @param mixed|null $default Default value to use when the parameter is missing. * @see http://www.faqs.org/rfcs/rfc3875.html * @return \Zend\Stdlib\ParametersInterface|mixed */ public function getServer($name = null, $default = null) { if ($this->serverParams === null) { $this->serverParams = new Parameters(); } if ($name === null) { return $this->serverParams; } return $this->serverParams->get($name, $default); } /** * Provide an alternate Parameter Container implementation for env parameters in this object, * (this is NOT the primary API for value setting, for that see env()) * * @param ParametersInterface $env * @return $this */ public function setEnv(ParametersInterface $env) { $this->envParams = $env; return $this; } /** * Return the parameter container responsible for env parameters or a single parameter value. * * @param string|null $name Parameter name to retrieve, or null to get the whole container. * @param mixed|null $default Default value to use when the parameter is missing. * @return \Zend\Stdlib\ParametersInterface|mixed */ public function getEnv($name = null, $default = null) { if ($this->envParams === null) { $this->envParams = new Parameters(); } if ($name === null) { return $this->envParams; } return $this->envParams->get($name, $default); } /** * Convert PHP superglobal $_FILES into more sane parameter=value structure * This handles form file input with brackets (name=files[]) * * @return array */ protected function mapPhpFiles() { $files = []; foreach ($_FILES as $fileName => $fileParams) { $files[$fileName] = []; foreach ($fileParams as $param => $data) { if (! is_array($data)) { $files[$fileName][$param] = $data; } else { foreach ($data as $i => $v) { $this->mapPhpFileParam($files[$fileName], $param, $i, $v); } } } } return $files; } /** * @param array $array * @param string $paramName * @param int|string $index * @param string|array $value */ protected function mapPhpFileParam(&$array, $paramName, $index, $value) { if (! is_array($value)) { $array[$index][$paramName] = $value; } else { foreach ($value as $i => $v) { $this->mapPhpFileParam($array[$index], $paramName, $i, $v); } } } /** * Detect the base URI for the request * * Looks at a variety of criteria in order to attempt to autodetect a base * URI, including rewrite URIs, proxy URIs, etc. * * @return string */ protected function detectRequestUri() { $requestUri = null; $server = $this->getServer(); // IIS7 with URL Rewrite: make sure we get the unencoded url // (double slash problem). $iisUrlRewritten = $server->get('IIS_WasUrlRewritten'); $unencodedUrl = $server->get('UNENCODED_URL', ''); if ('1' == $iisUrlRewritten && '' !== $unencodedUrl) { return $unencodedUrl; } $requestUri = $server->get('REQUEST_URI'); // HTTP proxy requests setup request URI with scheme and host [and port] // + the URL path, only use URL path. if ($requestUri !== null) { return preg_replace('#^[^/:]+://[^/]+#', '', $requestUri); } // IIS 5.0, PHP as CGI. $origPathInfo = $server->get('ORIG_PATH_INFO'); if ($origPathInfo !== null) { $queryString = $server->get('QUERY_STRING', ''); if ($queryString !== '') { $origPathInfo .= '?' . $queryString; } return $origPathInfo; } return '/'; } /** * Auto-detect the base path from the request environment * * Uses a variety of criteria in order to detect the base URL of the request * (i.e., anything additional to the document root). * * @return string */ protected function detectBaseUrl() { $filename = $this->getServer()->get('SCRIPT_FILENAME', ''); $scriptName = $this->getServer()->get('SCRIPT_NAME'); $phpSelf = $this->getServer()->get('PHP_SELF'); $origScriptName = $this->getServer()->get('ORIG_SCRIPT_NAME'); if ($scriptName !== null && basename($scriptName) === $filename) { $baseUrl = $scriptName; } elseif ($phpSelf !== null && basename($phpSelf) === $filename) { $baseUrl = $phpSelf; } elseif ($origScriptName !== null && basename($origScriptName) === $filename) { // 1and1 shared hosting compatibility. $baseUrl = $origScriptName; } else { // Backtrack up the SCRIPT_FILENAME to find the portion // matching PHP_SELF. // Only for CLI requests argv[0] contains script filename // @see https://www.php.net/manual/en/reserved.variables.server.php if (PHP_SAPI === 'cli') { $argv = $this->getServer()->get('argv', []); if (isset($argv[0]) && is_string($argv[0]) && $argv[0] !== '' && strpos($filename, $argv[0]) === 0) { $filename = substr($filename, strlen($argv[0])); } } $baseUrl = '/'; $basename = basename($filename); if ($basename) { $path = ($phpSelf ? trim($phpSelf, '/') : ''); $basePos = strpos($path, $basename) ?: 0; $baseUrl .= substr($path, 0, $basePos) . $basename; } } // If the baseUrl is empty, then simply return it. if (empty($baseUrl)) { return ''; } // Does the base URL have anything in common with the request URI? $requestUri = $this->getRequestUri(); // Full base URL matches. if (0 === strpos($requestUri, $baseUrl)) { return $baseUrl; } // Directory portion of base path matches. $baseDir = str_replace('\\', '/', dirname($baseUrl)); if (0 === strpos($requestUri, $baseDir)) { return $baseDir; } $truncatedRequestUri = $requestUri; if (false !== ($pos = strpos($requestUri, '?'))) { $truncatedRequestUri = substr($requestUri, 0, $pos); } $basename = basename($baseUrl); // No match whatsoever if (empty($basename) || false === strpos($truncatedRequestUri, $basename)) { return ''; } // If using mod_rewrite or ISAPI_Rewrite strip the script filename // out of the base path. $pos !== 0 makes sure it is not matching a // value from PATH_INFO or QUERY_STRING. if (strlen($requestUri) >= strlen($baseUrl) && (false !== ($pos = strpos($requestUri, $baseUrl)) && $pos !== 0) ) { $baseUrl = substr($requestUri, 0, $pos + strlen($baseUrl)); } return $baseUrl; } /** * Autodetect the base path of the request * * Uses several criteria to determine the base path of the request. * * @return string */ protected function detectBasePath() { $baseUrl = $this->getBaseUrl(); // Empty base url detected if ($baseUrl === '') { return ''; } $filename = basename($this->getServer()->get('SCRIPT_FILENAME', '')); // basename() matches the script filename; return the directory if (basename($baseUrl) === $filename) { return str_replace('\\', '/', dirname($baseUrl)); } // Base path is identical to base URL return $baseUrl; } }
php
BSD-3-Clause
ac4ffd09d509b2c5c0285178c4f7de740f05c3d9
2026-01-05T05:18:13.309357Z
false
zendframework/zend-http
https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/src/PhpEnvironment/Response.php
src/PhpEnvironment/Response.php
<?php /** * @see https://github.com/zendframework/zend-http for the canonical source repository * @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com) * @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License */ namespace Zend\Http\PhpEnvironment; use Zend\Http\Header\MultipleHeaderInterface; use Zend\Http\Response as HttpResponse; /** * HTTP Response for current PHP environment */ class Response extends HttpResponse { /** * The current used version * (The value will be detected on getVersion) * * @var null|string */ protected $version; /** * @var bool */ protected $contentSent = false; /** * Return the HTTP version for this response * * @return string * @see \Zend\Http\AbstractMessage::getVersion() */ public function getVersion() { if (! $this->version) { $this->version = $this->detectVersion(); } return $this->version; } /** * Detect the current used protocol version. * If detection failed it falls back to version 1.0. * * @return string */ protected function detectVersion() { if (isset($_SERVER['SERVER_PROTOCOL']) && $_SERVER['SERVER_PROTOCOL'] == 'HTTP/1.1') { return self::VERSION_11; } return self::VERSION_10; } /** * @return bool */ public function headersSent() { return headers_sent(); } /** * @return bool */ public function contentSent() { return $this->contentSent; } /** * Send HTTP headers * * @return $this */ public function sendHeaders() { if ($this->headersSent()) { return $this; } $status = $this->renderStatusLine(); header($status); /** @var \Zend\Http\Header\HeaderInterface $header */ foreach ($this->getHeaders() as $header) { if ($header instanceof MultipleHeaderInterface) { header($header->toString(), false); continue; } header($header->toString()); } $this->headersSent = true; return $this; } /** * Send content * * @return $this */ public function sendContent() { if ($this->contentSent()) { return $this; } echo $this->getContent(); $this->contentSent = true; return $this; } /** * Send HTTP response * * @return $this */ public function send() { $this->sendHeaders() ->sendContent(); return $this; } }
php
BSD-3-Clause
ac4ffd09d509b2c5c0285178c4f7de740f05c3d9
2026-01-05T05:18:13.309357Z
false
zendframework/zend-http
https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/src/Header/MultipleHeaderInterface.php
src/Header/MultipleHeaderInterface.php
<?php /** * @see https://github.com/zendframework/zend-http for the canonical source repository * @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com) * @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License */ namespace Zend\Http\Header; interface MultipleHeaderInterface extends HeaderInterface { public function toStringMultipleHeaders(array $headers); }
php
BSD-3-Clause
ac4ffd09d509b2c5c0285178c4f7de740f05c3d9
2026-01-05T05:18:13.309357Z
false
zendframework/zend-http
https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/src/Header/MaxForwards.php
src/Header/MaxForwards.php
<?php /** * @see https://github.com/zendframework/zend-http for the canonical source repository * @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com) * @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License */ namespace Zend\Http\Header; /** * @throws Exception\InvalidArgumentException * @see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.31 */ class MaxForwards implements HeaderInterface { /** * @var string */ protected $value; public static function fromString($headerLine) { list($name, $value) = GenericHeader::splitHeaderLine($headerLine); // check to ensure proper header type for this factory if (strtolower($name) !== 'max-forwards') { throw new Exception\InvalidArgumentException(sprintf( 'Invalid header line for Max-Forwards string: "%s"', $name )); } // @todo implementation details return new static($value); } public function __construct($value = null) { if ($value !== null) { HeaderValue::assertValid($value); $this->value = $value; } } public function getFieldName() { return 'Max-Forwards'; } public function getFieldValue() { return (string) $this->value; } public function toString() { return 'Max-Forwards: ' . $this->getFieldValue(); } }
php
BSD-3-Clause
ac4ffd09d509b2c5c0285178c4f7de740f05c3d9
2026-01-05T05:18:13.309357Z
false
zendframework/zend-http
https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/src/Header/RetryAfter.php
src/Header/RetryAfter.php
<?php /** * @see https://github.com/zendframework/zend-http for the canonical source repository * @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com) * @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License */ namespace Zend\Http\Header; /** * Retry-After HTTP Header * * @link http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.37 */ class RetryAfter extends AbstractDate { /** * Value of header in delta-seconds * By default set to 1 hour * * @var int */ protected $deltaSeconds = 3600; /** * Create Retry-After header from string * * @param string $headerLine * @return static * @throws Exception\InvalidArgumentException */ public static function fromString($headerLine) { $dateHeader = new static(); list($name, $date) = GenericHeader::splitHeaderLine($headerLine); // check to ensure proper header type for this factory if (strtolower($name) !== strtolower($dateHeader->getFieldName())) { throw new Exception\InvalidArgumentException( 'Invalid header line for "' . $dateHeader->getFieldName() . '" header string' ); } if (is_numeric($date)) { $dateHeader->setDeltaSeconds($date); } else { $dateHeader->setDate($date); } return $dateHeader; } /** * Set number of seconds * * @param int $delta * @return $this */ public function setDeltaSeconds($delta) { $this->deltaSeconds = (int) $delta; return $this; } /** * Get number of seconds * * @return int */ public function getDeltaSeconds() { return $this->deltaSeconds; } /** * Get header name * * @return string */ public function getFieldName() { return 'Retry-After'; } /** * Returns date if it's set, or number of seconds * * @return int|string */ public function getFieldValue() { return ($this->date === null) ? $this->deltaSeconds : $this->getDate(); } /** * Return header line * * @return string */ public function toString() { return 'Retry-After: ' . $this->getFieldValue(); } }
php
BSD-3-Clause
ac4ffd09d509b2c5c0285178c4f7de740f05c3d9
2026-01-05T05:18:13.309357Z
false
zendframework/zend-http
https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/src/Header/HeaderValue.php
src/Header/HeaderValue.php
<?php /** * @see https://github.com/zendframework/zend-http for the canonical source repository * @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com) * @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License */ namespace Zend\Http\Header; final class HeaderValue { /** * Private constructor; non-instantiable. */ private function __construct() { } /** * Filter a header value * * Ensures CRLF header injection vectors are filtered. * * Per RFC 7230, only VISIBLE ASCII characters, spaces, and horizontal * tabs are allowed in values; only one whitespace character is allowed * between visible characters. * * @see http://en.wikipedia.org/wiki/HTTP_response_splitting * @param string $value * @return string */ public static function filter($value) { $value = (string) $value; $length = strlen($value); $string = ''; for ($i = 0; $i < $length; $i += 1) { $ascii = ord($value[$i]); // Non-visible, non-whitespace characters // 9 === horizontal tab // 32-126, 128-254 === visible // 127 === DEL // 255 === null byte if (($ascii < 32 && $ascii !== 9) || $ascii === 127 || $ascii > 254 ) { continue; } $string .= $value[$i]; } return $string; } /** * Validate a header value. * * Per RFC 7230, only VISIBLE ASCII characters, spaces, and horizontal * tabs are allowed in values; only one whitespace character is allowed * between visible characters. * * @see http://en.wikipedia.org/wiki/HTTP_response_splitting * @param string $value * @return bool */ public static function isValid($value) { $value = (string) $value; $length = strlen($value); for ($i = 0; $i < $length; $i += 1) { $ascii = ord($value[$i]); // Non-visible, non-whitespace characters // 9 === horizontal tab // 32-126, 128-254 === visible // 127 === DEL // 255 === null byte if (($ascii < 32 && $ascii !== 9) || $ascii === 127 || $ascii > 254 ) { return false; } } return true; } /** * Assert a header value is valid. * * @param string $value * @throws Exception\RuntimeException for invalid values * @return void */ public static function assertValid($value) { if (! self::isValid($value)) { throw new Exception\InvalidArgumentException('Invalid header value'); } } }
php
BSD-3-Clause
ac4ffd09d509b2c5c0285178c4f7de740f05c3d9
2026-01-05T05:18:13.309357Z
false
zendframework/zend-http
https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/src/Header/GenericHeader.php
src/Header/GenericHeader.php
<?php /** * @see https://github.com/zendframework/zend-http for the canonical source repository * @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com) * @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License */ namespace Zend\Http\Header; /** * Content-Location Header */ class GenericHeader implements HeaderInterface { /** * @var string */ protected $fieldName; /** * @var string */ protected $fieldValue; /** * Factory to generate a header object from a string * * @param string $headerLine * @return static */ public static function fromString($headerLine) { list($fieldName, $fieldValue) = GenericHeader::splitHeaderLine($headerLine); return new static($fieldName, $fieldValue); } /** * Splits the header line in `name` and `value` parts. * * @param string $headerLine * @return string[] `name` in the first index and `value` in the second. * @throws Exception\InvalidArgumentException If header does not match with the format ``name:value`` */ public static function splitHeaderLine($headerLine) { $parts = explode(':', $headerLine, 2); if (count($parts) !== 2) { throw new Exception\InvalidArgumentException('Header must match with the format "name:value"'); } if (! HeaderValue::isValid($parts[1])) { throw new Exception\InvalidArgumentException('Invalid header value detected'); } $parts[1] = ltrim($parts[1]); return $parts; } /** * Constructor * * @param null|string $fieldName * @param null|string $fieldValue */ public function __construct($fieldName = null, $fieldValue = null) { if ($fieldName) { $this->setFieldName($fieldName); } if ($fieldValue !== null) { $this->setFieldValue($fieldValue); } } /** * Set header field name * * @param string $fieldName * @return $this * @throws Exception\InvalidArgumentException If the name does not match with RFC 2616 format. */ public function setFieldName($fieldName) { if (! is_string($fieldName) || empty($fieldName)) { throw new Exception\InvalidArgumentException('Header name must be a string'); } /* * Following RFC 7230 section 3.2 * * header-field = field-name ":" [ field-value ] * field-name = token * token = 1*tchar * tchar = "!" / "#" / "$" / "%" / "&" / "'" / "*" / "+" / "-" / "." / * "^" / "_" / "`" / "|" / "~" / DIGIT / ALPHA */ if (! preg_match('/^[!#$%&\'*+\-\.\^_`|~0-9a-zA-Z]+$/', $fieldName)) { throw new Exception\InvalidArgumentException( 'Header name must be a valid RFC 7230 (section 3.2) field-name.' ); } $this->fieldName = $fieldName; return $this; } /** * Retrieve header field name * * @return string */ public function getFieldName() { return $this->fieldName; } /** * Set header field value * * @param string $fieldValue * @return $this */ public function setFieldValue($fieldValue) { $fieldValue = (string) $fieldValue; HeaderValue::assertValid($fieldValue); if (preg_match('/^\s+$/', $fieldValue)) { $fieldValue = ''; } $this->fieldValue = $fieldValue; return $this; } /** * Retrieve header field value * * @return string */ public function getFieldValue() { return $this->fieldValue; } /** * Cast to string as a well formed HTTP header line * * Returns in form of "NAME: VALUE\r\n" * * @return string */ public function toString() { return $this->getFieldName() . ': ' . $this->getFieldValue(); } }
php
BSD-3-Clause
ac4ffd09d509b2c5c0285178c4f7de740f05c3d9
2026-01-05T05:18:13.309357Z
false
zendframework/zend-http
https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/src/Header/Etag.php
src/Header/Etag.php
<?php /** * @see https://github.com/zendframework/zend-http for the canonical source repository * @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com) * @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License */ namespace Zend\Http\Header; /** * @throws Exception\InvalidArgumentException * @see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.19 */ class Etag implements HeaderInterface { /** * @var string */ protected $value; public static function fromString($headerLine) { list($name, $value) = GenericHeader::splitHeaderLine($headerLine); // check to ensure proper header type for this factory if (strtolower($name) !== 'etag') { throw new Exception\InvalidArgumentException('Invalid header line for Etag string: "' . $name . '"'); } // @todo implementation details return new static($value); } public function __construct($value = null) { if ($value !== null) { HeaderValue::assertValid($value); $this->value = $value; } } public function getFieldName() { return 'Etag'; } public function getFieldValue() { return (string) $this->value; } public function toString() { return 'Etag: ' . $this->getFieldValue(); } }
php
BSD-3-Clause
ac4ffd09d509b2c5c0285178c4f7de740f05c3d9
2026-01-05T05:18:13.309357Z
false
zendframework/zend-http
https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/src/Header/Expires.php
src/Header/Expires.php
<?php /** * @see https://github.com/zendframework/zend-http for the canonical source repository * @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com) * @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License */ namespace Zend\Http\Header; /** * Expires Header * * @link http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.21 */ class Expires extends AbstractDate { /** * Get header name * * @return string */ public function getFieldName() { return 'Expires'; } public function setDate($date) { if ($date === '0' || $date === 0) { $date = date(DATE_W3C, 0); // Thu, 01 Jan 1970 00:00:00 GMT } return parent::setDate($date); } }
php
BSD-3-Clause
ac4ffd09d509b2c5c0285178c4f7de740f05c3d9
2026-01-05T05:18:13.309357Z
false
zendframework/zend-http
https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/src/Header/Connection.php
src/Header/Connection.php
<?php /** * @see https://github.com/zendframework/zend-http for the canonical source repository * @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com) * @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License */ namespace Zend\Http\Header; /** * Connection Header * * @link http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.10 */ class Connection implements HeaderInterface { const CONNECTION_CLOSE = 'close'; const CONNECTION_KEEP_ALIVE = 'keep-alive'; /** * Value of this header * * @var string */ protected $value = self::CONNECTION_KEEP_ALIVE; /** * @param string $headerLine * @return static * @throws Exception\InvalidArgumentException */ public static function fromString($headerLine) { $header = new static(); list($name, $value) = GenericHeader::splitHeaderLine($headerLine); // check to ensure proper header type for this factory if (strtolower($name) !== 'connection') { throw new Exception\InvalidArgumentException('Invalid header line for Connection string: "' . $name . '"'); } $header->setValue(trim($value)); return $header; } /** * Set Connection header to define persistent connection * * @param bool $flag * @return $this */ public function setPersistent($flag) { $this->value = (bool) $flag ? self::CONNECTION_KEEP_ALIVE : self::CONNECTION_CLOSE; return $this; } /** * Get whether this connection is persistent * * @return bool */ public function isPersistent() { return ($this->value === self::CONNECTION_KEEP_ALIVE); } /** * Set arbitrary header value * RFC allows any token as value, 'close' and 'keep-alive' are commonly used * * @param string $value * @return $this */ public function setValue($value) { HeaderValue::assertValid($value); $this->value = strtolower($value); return $this; } /** * Connection header name * * @return string */ public function getFieldName() { return 'Connection'; } /** * Connection header value * * @return string */ public function getFieldValue() { return $this->value; } /** * Return header line * * @return string */ public function toString() { return 'Connection: ' . $this->getFieldValue(); } }
php
BSD-3-Clause
ac4ffd09d509b2c5c0285178c4f7de740f05c3d9
2026-01-05T05:18:13.309357Z
false
zendframework/zend-http
https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/src/Header/HeaderInterface.php
src/Header/HeaderInterface.php
<?php /** * @see https://github.com/zendframework/zend-http for the canonical source repository * @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com) * @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License */ namespace Zend\Http\Header; /** * Interface for HTTP Header classes. */ interface HeaderInterface { /** * Factory to generate a header object from a string * * @param string $headerLine * @return static * @throws Exception\InvalidArgumentException If the header does not match RFC 2616 definition. * @see http://tools.ietf.org/html/rfc2616#section-4.2 */ public static function fromString($headerLine); /** * Retrieve header name * * @return string */ public function getFieldName(); /** * Retrieve header value * * @return string */ public function getFieldValue(); /** * Cast to string * * Returns in form of "NAME: VALUE" * * @return string */ public function toString(); }
php
BSD-3-Clause
ac4ffd09d509b2c5c0285178c4f7de740f05c3d9
2026-01-05T05:18:13.309357Z
false
zendframework/zend-http
https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/src/Header/AbstractAccept.php
src/Header/AbstractAccept.php
<?php /** * @see https://github.com/zendframework/zend-http for the canonical source repository * @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com) * @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License */ namespace Zend\Http\Header; use stdClass; /** * Abstract Accept Header * * Naming conventions: * * Accept: audio/mp3; q=0.2; version=0.5, audio/basic+mp3 * |------------------------------------------------------| header line * |------| field name * |-----------------------------------------------| field value * |-------------------------------| field value part * |------| type * |--| subtype * |--| format * |----| subtype * |---| format * |-------------------| parameter set * |-----------| parameter * |-----| parameter key * |--| parameter value * |---| priority * * * @see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.1 * @author Dolf Schimmel - Freeaqingme */ abstract class AbstractAccept implements HeaderInterface { /** * @var stdClass[] */ protected $fieldValueParts = []; protected $regexAddType; /** * Determines if since last mutation the stack was sorted * * @var bool */ protected $sorted = false; /** * Parse a full header line or just the field value part. * * @param string $headerLine */ public function parseHeaderLine($headerLine) { if (strpos($headerLine, ':') !== false) { list($name, $value) = GenericHeader::splitHeaderLine($headerLine); if (strtolower($name) !== strtolower($this->getFieldName())) { $value = $headerLine; // This is just for preserve the BC. } } else { $value = $headerLine; } HeaderValue::assertValid($value); foreach ($this->getFieldValuePartsFromHeaderLine($value) as $value) { $this->addFieldValuePartToQueue($value); } } /** * Factory method: parse Accept header string * * @param string $headerLine * @return static */ public static function fromString($headerLine) { $obj = new static(); $obj->parseHeaderLine($headerLine); return $obj; } /** * Parse the Field Value Parts represented by a header line * * @param string $headerLine * @throws Exception\InvalidArgumentException If header is invalid * @return array */ public function getFieldValuePartsFromHeaderLine($headerLine) { // process multiple accept values, they may be between quotes if (! preg_match_all('/(?:[^,"]|"(?:[^\\\"]|\\\.)*")+/', $headerLine, $values) || ! isset($values[0]) ) { throw new Exception\InvalidArgumentException( 'Invalid header line for ' . $this->getFieldName() . ' header string' ); } $out = []; foreach ($values[0] as $value) { $value = trim($value); $out[] = $this->parseFieldValuePart($value); } return $out; } /** * Parse the accept params belonging to a media range * * @param string $fieldValuePart * @return stdClass */ protected function parseFieldValuePart($fieldValuePart) { $raw = $subtypeWhole = $type = $fieldValuePart; if ($pos = strpos($fieldValuePart, ';')) { $type = substr($fieldValuePart, 0, $pos); } $params = $this->getParametersFromFieldValuePart($fieldValuePart); if ($pos = strpos($fieldValuePart, ';')) { $fieldValuePart = trim(substr($fieldValuePart, 0, $pos)); } $format = '*'; $subtype = '*'; return (object) [ 'typeString' => trim($fieldValuePart), 'type' => $type, 'subtype' => $subtype, 'subtypeRaw' => $subtypeWhole, 'format' => $format, 'priority' => isset($params['q']) ? $params['q'] : 1, 'params' => $params, 'raw' => trim($raw), ]; } /** * Parse the keys contained in the header line * * @param string $fieldValuePart * @return array */ protected function getParametersFromFieldValuePart($fieldValuePart) { $params = []; if ((($pos = strpos($fieldValuePart, ';')) !== false)) { preg_match_all('/(?:[^;"]|"(?:[^\\\"]|\\\.)*")+/', $fieldValuePart, $paramsStrings); if (isset($paramsStrings[0])) { array_shift($paramsStrings[0]); $paramsStrings = $paramsStrings[0]; } foreach ($paramsStrings as $param) { $explode = explode('=', $param, 2); if (count($explode) === 2) { $value = trim($explode[1]); } else { $value = null; } if (isset($value[0]) && $value[0] == '"' && substr($value, -1) == '"') { $value = substr(substr($value, 1), 0, -1); } $params[trim($explode[0])] = stripslashes($value); } } return $params; } /** * Get field value * * @param array|null $values * @return string */ public function getFieldValue($values = null) { if ($values === null) { return $this->getFieldValue($this->fieldValueParts); } $strings = []; foreach ($values as $value) { $params = $value->params; array_walk($params, [$this, 'assembleAcceptParam']); $strings[] = implode(';', [$value->typeString] + $params); } return implode(', ', $strings); } /** * Assemble and escape the field value parameters based on RFC 2616 section 2.1 * * @todo someone should review this thoroughly * @param string $value * @param string $key * @return string */ protected function assembleAcceptParam(&$value, $key) { $separators = ['(', ')', '<', '>', '@', ',', ';', ':', '/', '[', ']', '?', '=', '{', '}', ' ', "\t"]; $escaped = preg_replace_callback( '/[[:cntrl:]"\\\\]/', // escape cntrl, ", \ function ($v) { return '\\' . $v[0]; }, $value ); if ($escaped == $value && ! array_intersect(str_split($value), $separators)) { $value = $key . ($value ? '=' . $value : ''); } else { $value = $key . ($value ? '="' . $escaped . '"' : ''); } return $value; } /** * Add a type, with the given priority * * @param string $type * @param int|float $priority * @param array (optional) $params * @throws Exception\InvalidArgumentException * @return $this */ protected function addType($type, $priority = 1, array $params = []) { if (! preg_match($this->regexAddType, $type)) { throw new Exception\InvalidArgumentException(sprintf( '%s expects a valid type; received "%s"', __METHOD__, (string) $type )); } if (! is_int($priority) && ! is_float($priority) && ! is_numeric($priority) || $priority > 1 || $priority < 0 ) { throw new Exception\InvalidArgumentException(sprintf( '%s expects a numeric priority; received %s', __METHOD__, (string) $priority )); } if ($priority != 1) { $params = ['q' => sprintf('%01.1f', $priority)] + $params; } $assembledString = $this->getFieldValue( [(object) ['typeString' => $type, 'params' => $params]] ); $value = $this->parseFieldValuePart($assembledString); $this->addFieldValuePartToQueue($value); return $this; } /** * Does the header have the requested type? * * @param array|string $matchAgainst * @return bool */ protected function hasType($matchAgainst) { return (bool) $this->match($matchAgainst); } /** * Match a media string against this header * * @param array|string $matchAgainst * @return Accept\FieldValuePArt\AcceptFieldValuePart|bool The matched value or false */ public function match($matchAgainst) { if (is_string($matchAgainst)) { $matchAgainst = $this->getFieldValuePartsFromHeaderLine($matchAgainst); } foreach ($this->getPrioritized() as $left) { foreach ($matchAgainst as $right) { if ($right->type == '*' || $left->type == '*') { if ($this->matchAcceptParams($left, $right)) { $left->setMatchedAgainst($right); return $left; } } if ($left->type == $right->type) { if (($left->subtype == $right->subtype || ($right->subtype == '*' || $left->subtype == '*')) && ($left->format == $right->format || $right->format == '*' || $left->format == '*') ) { if ($this->matchAcceptParams($left, $right)) { $left->setMatchedAgainst($right); return $left; } } } } } return false; } /** * Return a match where all parameters in argument #1 match those in argument #2 * * @param array $match1 * @param array $match2 * @return bool|array */ protected function matchAcceptParams($match1, $match2) { foreach ($match2->params as $key => $value) { if (isset($match1->params[$key])) { if (strpos($value, '-')) { preg_match( '/^(?|([^"-]*)|"([^"]*)")-(?|([^"-]*)|"([^"]*)")\z/', $value, $pieces ); if (count($pieces) == 3 && (version_compare($pieces[1], $match1->params[$key], '<=') xor version_compare($pieces[2], $match1->params[$key], '>=')) ) { return false; } } elseif (strpos($value, '|')) { $options = explode('|', $value); $good = false; foreach ($options as $option) { if ($option == $match1->params[$key]) { $good = true; break; } } if (! $good) { return false; } } elseif ($match1->params[$key] != $value) { return false; } } } return $match1; } /** * Add a key/value combination to the internal queue * * @param stdClass $value * @return number */ protected function addFieldValuePartToQueue($value) { $this->fieldValueParts[] = $value; $this->sorted = false; } /** * Sort the internal Field Value Parts * * @See rfc2616 sect 14.1 * Media ranges can be overridden by more specific media ranges or * specific media types. If more than one media range applies to a given * type, the most specific reference has precedence. For example, * * Accept: text/*, text/html, text/html;level=1, * /* * * have the following precedence: * * 1) text/html;level=1 * 2) text/html * 3) text/* * 4) * /* * * @return number */ protected function sortFieldValueParts() { $sort = function ($a, $b) { // If A has higher precedence than B, return -1. if ($a->priority > $b->priority) { return -1; } elseif ($a->priority < $b->priority) { return 1; } // Asterisks $values = ['type', 'subtype', 'format']; foreach ($values as $value) { if ($a->$value == '*' && $b->$value != '*') { return 1; } elseif ($b->$value == '*' && $a->$value != '*') { return -1; } } if ($a->type == 'application' && $b->type != 'application') { return -1; } elseif ($b->type == 'application' && $a->type != 'application') { return 1; } // @todo count number of dots in case of type==application in subtype // So far they're still the same. Longest string length may be more specific if (strlen($a->raw) == strlen($b->raw)) { return 0; } return (strlen($a->raw) > strlen($b->raw)) ? -1 : 1; }; usort($this->fieldValueParts, $sort); $this->sorted = true; } /** * @return array with all the keys, values and parameters this header represents: */ public function getPrioritized() { if (! $this->sorted) { $this->sortFieldValueParts(); } return $this->fieldValueParts; } }
php
BSD-3-Clause
ac4ffd09d509b2c5c0285178c4f7de740f05c3d9
2026-01-05T05:18:13.309357Z
false
zendframework/zend-http
https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/src/Header/SetCookie.php
src/Header/SetCookie.php
<?php /** * @see https://github.com/zendframework/zend-http for the canonical source repository * @copyright Copyright (c) 2005-2019 Zend Technologies USA Inc. (https://www.zend.com) * @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License */ namespace Zend\Http\Header; use DateTime; use Zend\Uri\UriFactory; use function array_key_exists; use function gettype; use function is_scalar; use function strtolower; /** * @throws Exception\InvalidArgumentException * @see http://www.ietf.org/rfc/rfc2109.txt * @see http://www.w3.org/Protocols/rfc2109/rfc2109 */ class SetCookie implements MultipleHeaderInterface { /** * Cookie will not be sent for any cross-domain requests whatsoever. * Even if the user simply navigates to the target site with a regular link, the cookie will not be sent. */ const SAME_SITE_STRICT = 'Strict'; /** * Cookie will not be passed for any cross-domain requests unless it's a regular link that navigates user * to the target site. * Other requests methods (such as POST and PUT) and XHR requests will not contain this cookie. */ const SAME_SITE_LAX = 'Lax'; /** * Cookie will be sent with same-site and cross-site requests. */ const SAME_SITE_NONE = 'None'; /** * @internal */ const SAME_SITE_ALLOWED_VALUES = [ 'strict' => self::SAME_SITE_STRICT, 'lax' => self::SAME_SITE_LAX, 'none' => self::SAME_SITE_NONE, ]; /** * Cookie name * * @var string|null */ protected $name; /** * Cookie value * * @var string|null */ protected $value; /** * Version * * @var int|null */ protected $version; /** * Max Age * * @var int|null */ protected $maxAge; /** * Cookie expiry date * * @var int|null */ protected $expires; /** * Cookie domain * * @var string|null */ protected $domain; /** * Cookie path * * @var string|null */ protected $path; /** * Whether the cookie is secure or not * * @var bool|null */ protected $secure; /** * If the value need to be quoted or not * * @var bool */ protected $quoteFieldValue = false; /** * @var bool|null */ protected $httponly; /** * @var string|null */ protected $sameSite; /** * @var bool */ protected $encodeValue = true; /** * @static * @throws Exception\InvalidArgumentException * @param $headerLine * @param bool $bypassHeaderFieldName * @return array|SetCookie */ public static function fromString($headerLine, $bypassHeaderFieldName = false) { static $setCookieProcessor = null; if ($setCookieProcessor === null) { $setCookieClass = get_called_class(); $setCookieProcessor = function ($headerLine) use ($setCookieClass) { /** @var SetCookie $header */ $header = new $setCookieClass(); $keyValuePairs = preg_split('#;\s*#', $headerLine); foreach ($keyValuePairs as $keyValue) { if (preg_match('#^(?P<headerKey>[^=]+)=\s*("?)(?P<headerValue>[^"]*)\2#', $keyValue, $matches)) { $headerKey = $matches['headerKey']; $headerValue = $matches['headerValue']; } else { $headerKey = $keyValue; $headerValue = null; } // First K=V pair is always the cookie name and value if ($header->getName() === null) { $header->setName($headerKey); $header->setValue(urldecode($headerValue)); // set no encode value if raw and encoded values are the same if (urldecode($headerValue) === $headerValue) { $header->setEncodeValue(false); } continue; } // Process the remaining elements switch (str_replace(['-', '_'], '', strtolower($headerKey))) { case 'expires': $header->setExpires($headerValue); break; case 'domain': $header->setDomain($headerValue); break; case 'path': $header->setPath($headerValue); break; case 'secure': $header->setSecure(true); break; case 'httponly': $header->setHttponly(true); break; case 'version': $header->setVersion((int) $headerValue); break; case 'maxage': $header->setMaxAge($headerValue); break; case 'samesite': $header->setSameSite($headerValue); break; default: // Intentionally omitted } } return $header; }; } list($name, $value) = GenericHeader::splitHeaderLine($headerLine); HeaderValue::assertValid($value); // some sites return set-cookie::value, this is to get rid of the second : $name = strtolower($name) == 'set-cookie:' ? 'set-cookie' : $name; // check to ensure proper header type for this factory if (strtolower($name) !== 'set-cookie') { throw new Exception\InvalidArgumentException('Invalid header line for Set-Cookie string: "' . $name . '"'); } $multipleHeaders = preg_split('#(?<!Sun|Mon|Tue|Wed|Thu|Fri|Sat),\s*#', $value); if (count($multipleHeaders) <= 1) { return $setCookieProcessor(array_pop($multipleHeaders)); } else { $headers = []; foreach ($multipleHeaders as $headerLine) { $headers[] = $setCookieProcessor($headerLine); } return $headers; } } /** * Cookie object constructor * * @todo Add validation of each one of the parameters (legal domain, etc.) * * @param string|null $name * @param string|null $value * @param int|string|DateTime|null $expires * @param string|null $path * @param string|null $domain * @param bool $secure * @param bool $httponly * @param int|null $maxAge * @param int|null $version * @param string|null $sameSite */ public function __construct( $name = null, $value = null, $expires = null, $path = null, $domain = null, $secure = false, $httponly = false, $maxAge = null, $version = null, $sameSite = null ) { $this->type = 'Cookie'; $this->setName($name) ->setValue($value) ->setVersion($version) ->setMaxAge($maxAge) ->setDomain($domain) ->setExpires($expires) ->setPath($path) ->setSecure($secure) ->setHttpOnly($httponly) ->setSameSite($sameSite); } /** * @return bool */ public function getEncodeValue() { return $this->encodeValue; } /** * @param bool $encodeValue */ public function setEncodeValue($encodeValue) { $this->encodeValue = (bool) $encodeValue; } /** * @return string 'Set-Cookie' */ public function getFieldName() { return 'Set-Cookie'; } /** * @throws Exception\RuntimeException * @return string */ public function getFieldValue() { if ($this->getName() == '') { return ''; } $value = $this->encodeValue ? urlencode($this->getValue()) : $this->getValue(); if ($this->hasQuoteFieldValue()) { $value = '"' . $value . '"'; } $fieldValue = $this->getName() . '=' . $value; $version = $this->getVersion(); if ($version !== null) { $fieldValue .= '; Version=' . $version; } $maxAge = $this->getMaxAge(); if ($maxAge !== null) { $fieldValue .= '; Max-Age=' . $maxAge; } $expires = $this->getExpires(); if ($expires) { $fieldValue .= '; Expires=' . $expires; } $domain = $this->getDomain(); if ($domain) { $fieldValue .= '; Domain=' . $domain; } $path = $this->getPath(); if ($path) { $fieldValue .= '; Path=' . $path; } if ($this->isSecure()) { $fieldValue .= '; Secure'; } if ($this->isHttponly()) { $fieldValue .= '; HttpOnly'; } $sameSite = $this->getSameSite(); if ($sameSite !== null && array_key_exists(strtolower($sameSite), self::SAME_SITE_ALLOWED_VALUES)) { $fieldValue .= '; SameSite=' . $sameSite; } return $fieldValue; } /** * @param string|null $name * @return $this * @throws Exception\InvalidArgumentException */ public function setName($name) { HeaderValue::assertValid($name); $this->name = $name; return $this; } /** * @return string|null */ public function getName() { return $this->name; } /** * @param string|null $value * @return $this */ public function setValue($value) { $this->value = $value; return $this; } /** * @return string|null */ public function getValue() { return $this->value; } /** * @param int|null $version * @return $this * @throws Exception\InvalidArgumentException */ public function setVersion($version) { if ($version !== null && ! is_int($version)) { throw new Exception\InvalidArgumentException('Invalid Version number specified'); } $this->version = $version; return $this; } /** * @return int|null */ public function getVersion() { return $this->version; } /** * @param int $maxAge * @return $this */ public function setMaxAge($maxAge) { if ($maxAge === null || ! is_numeric($maxAge)) { return $this; } $this->maxAge = max(0, (int) $maxAge); return $this; } /** * @return int|null */ public function getMaxAge() { return $this->maxAge; } /** * @param int|string|DateTime|null $expires * @return $this * @throws Exception\InvalidArgumentException */ public function setExpires($expires) { if ($expires === null) { $this->expires = null; return $this; } if ($expires instanceof DateTime) { $expires = $expires->format(DateTime::COOKIE); } $tsExpires = $expires; if (is_string($expires)) { $tsExpires = strtotime($expires); // if $tsExpires is invalid and PHP is compiled as 32bit. Check if it fail reason is the 2038 bug if (! is_int($tsExpires) && PHP_INT_SIZE === 4) { $dateTime = new DateTime($expires); if ($dateTime->format('Y') > 2038) { $tsExpires = PHP_INT_MAX; } } } if (! is_int($tsExpires) || $tsExpires < 0) { throw new Exception\InvalidArgumentException('Invalid expires time specified'); } $this->expires = $tsExpires; return $this; } /** * @param bool $inSeconds * @return int|string|null */ public function getExpires($inSeconds = false) { if ($this->expires === null) { return null; } if ($inSeconds) { return $this->expires; } return gmdate('D, d-M-Y H:i:s', $this->expires) . ' GMT'; } /** * @param string|null $domain * @return $this */ public function setDomain($domain) { HeaderValue::assertValid($domain); $this->domain = $domain; return $this; } /** * @return string|null */ public function getDomain() { return $this->domain; } /** * @param string|null $path * @return $this */ public function setPath($path) { HeaderValue::assertValid($path); $this->path = $path; return $this; } /** * @return string|null */ public function getPath() { return $this->path; } /** * @param bool|null $secure * @return $this */ public function setSecure($secure) { if (null !== $secure) { $secure = (bool) $secure; } $this->secure = $secure; return $this; } /** * Set whether the value for this cookie should be quoted * * @param bool $quotedValue * @return $this */ public function setQuoteFieldValue($quotedValue) { $this->quoteFieldValue = (bool) $quotedValue; return $this; } /** * @return bool|null */ public function isSecure() { return $this->secure; } /** * @param bool|null $httponly * @return $this */ public function setHttponly($httponly) { if (null !== $httponly) { $httponly = (bool) $httponly; } $this->httponly = $httponly; return $this; } /** * @return bool|null */ public function isHttponly() { return $this->httponly; } /** * Check whether the cookie has expired * * Always returns false if the cookie is a session cookie (has no expiry time) * * @param int|null $now Timestamp to consider as "now" * @return bool */ public function isExpired($now = null) { if ($now === null) { $now = time(); } if (is_int($this->expires) && $this->expires < $now) { return true; } return false; } /** * Check whether the cookie is a session cookie (has no expiry time set) * * @return bool */ public function isSessionCookie() { return ($this->expires === null); } /** * @return string|null */ public function getSameSite() { return $this->sameSite; } /** * @param string|null $sameSite * @return $this * @throws Exception\InvalidArgumentException */ public function setSameSite($sameSite) { if ($sameSite === null) { $this->sameSite = null; return $this; } if (! array_key_exists(strtolower($sameSite), self::SAME_SITE_ALLOWED_VALUES)) { throw new Exception\InvalidArgumentException(sprintf( 'Invalid value provided for SameSite directive: "%s"; expected one of: Strict, Lax or None', is_scalar($sameSite) ? $sameSite : gettype($sameSite) )); } $this->sameSite = self::SAME_SITE_ALLOWED_VALUES[strtolower($sameSite)]; return $this; } /** * Check whether the value for this cookie should be quoted * * @return bool */ public function hasQuoteFieldValue() { return $this->quoteFieldValue; } /** * @param string $requestDomain * @param string $path * @param bool $isSecure * @return bool */ public function isValidForRequest($requestDomain, $path, $isSecure = false) { if ($this->getDomain() && (strrpos($requestDomain, $this->getDomain()) === false)) { return false; } if ($this->getPath() && (strpos($path, $this->getPath()) !== 0)) { return false; } if ($this->secure && $this->isSecure() !== $isSecure) { return false; } return true; } /** * Checks whether the cookie should be sent or not in a specific scenario * * @param string|\Zend\Uri\Uri $uri URI to check against (secure, domain, path) * @param bool $matchSessionCookies Whether to send session cookies * @param int|null $now Override the current time when checking for expiry time * @return bool * @throws Exception\InvalidArgumentException If URI does not have HTTP or HTTPS scheme. */ public function match($uri, $matchSessionCookies = true, $now = null) { if (is_string($uri)) { $uri = UriFactory::factory($uri); } // Make sure we have a valid Zend_Uri_Http object if (! ($uri->isValid() && ($uri->getScheme() == 'http' || $uri->getScheme() == 'https'))) { throw new Exception\InvalidArgumentException('Passed URI is not a valid HTTP or HTTPS URI'); } // Check that the cookie is secure (if required) and not expired if ($this->secure && $uri->getScheme() != 'https') { return false; } if ($this->isExpired($now)) { return false; } if ($this->isSessionCookie() && ! $matchSessionCookies) { return false; } // Check if the domain matches if (! self::matchCookieDomain($this->getDomain(), $uri->getHost())) { return false; } // Check that path matches using prefix match if (! self::matchCookiePath($this->getPath(), $uri->getPath())) { return false; } // If we didn't die until now, return true. return true; } /** * Check if a cookie's domain matches a host name. * * Used by Zend\Http\Cookies for cookie matching * * @param string $cookieDomain * @param string $host * @return bool */ public static function matchCookieDomain($cookieDomain, $host) { $cookieDomain = strtolower($cookieDomain); $host = strtolower($host); // Check for either exact match or suffix match return $cookieDomain == $host || preg_match('/' . preg_quote($cookieDomain) . '$/', $host); } /** * Check if a cookie's path matches a URL path * * Used by Zend\Http\Cookies for cookie matching * * @param string $cookiePath * @param string $path * @return bool */ public static function matchCookiePath($cookiePath, $path) { return (strpos($path, $cookiePath) === 0); } /** * @return string */ public function toString() { return 'Set-Cookie: ' . $this->getFieldValue(); } /** * @param array $headers * @return string * @throws Exception\RuntimeException */ public function toStringMultipleHeaders(array $headers) { $headerLine = $this->toString(); /* @var $header SetCookie */ foreach ($headers as $header) { if (! $header instanceof SetCookie) { throw new Exception\RuntimeException( 'The SetCookie multiple header implementation can only accept an array of SetCookie headers' ); } $headerLine .= "\n" . $header->toString(); } return $headerLine; } }
php
BSD-3-Clause
ac4ffd09d509b2c5c0285178c4f7de740f05c3d9
2026-01-05T05:18:13.309357Z
false
zendframework/zend-http
https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/src/Header/Authorization.php
src/Header/Authorization.php
<?php /** * @see https://github.com/zendframework/zend-http for the canonical source repository * @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com) * @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License */ namespace Zend\Http\Header; /** * @throws Exception\InvalidArgumentException * @see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.8 */ class Authorization implements HeaderInterface { /** * @var string */ protected $value; public static function fromString($headerLine) { list($name, $value) = GenericHeader::splitHeaderLine($headerLine); // check to ensure proper header type for this factory if (strtolower($name) !== 'authorization') { throw new Exception\InvalidArgumentException(sprintf( 'Invalid header line for Authorization string: "%s"', $name )); } // @todo implementation details return new static($value); } public function __construct($value = null) { if ($value !== null) { HeaderValue::assertValid($value); $this->value = $value; } } public function getFieldName() { return 'Authorization'; } public function getFieldValue() { return (string) $this->value; } public function toString() { return 'Authorization: ' . $this->getFieldValue(); } }
php
BSD-3-Clause
ac4ffd09d509b2c5c0285178c4f7de740f05c3d9
2026-01-05T05:18:13.309357Z
false
zendframework/zend-http
https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/src/Header/AcceptEncoding.php
src/Header/AcceptEncoding.php
<?php /** * @see https://github.com/zendframework/zend-http for the canonical source repository * @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com) * @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License */ namespace Zend\Http\Header; use Zend\Http\Header\Accept\FieldValuePart; /** * Accept Encoding Header * * @see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.3 */ class AcceptEncoding extends AbstractAccept { protected $regexAddType = '#^([a-zA-Z0-9+-]+|\*)$#'; /** * Get field name * * @return string */ public function getFieldName() { return 'Accept-Encoding'; } /** * Cast to string * * @return string */ public function toString() { return 'Accept-Encoding: ' . $this->getFieldValue(); } /** * Add an encoding, with the given priority * * @param string $type * @param int|float $priority * @return $this */ public function addEncoding($type, $priority = 1) { return $this->addType($type, $priority); } /** * Does the header have the requested encoding? * * @param string $type * @return bool */ public function hasEncoding($type) { return $this->hasType($type); } /** * Parse the keys contained in the header line * * @param string $fieldValuePart * @return \Zend\Http\Header\Accept\FieldValuePart\EncodingFieldValuePart * @see \Zend\Http\Header\AbstractAccept::parseFieldValuePart() */ protected function parseFieldValuePart($fieldValuePart) { $internalValues = parent::parseFieldValuePart($fieldValuePart); return new FieldValuePart\EncodingFieldValuePart($internalValues); } }
php
BSD-3-Clause
ac4ffd09d509b2c5c0285178c4f7de740f05c3d9
2026-01-05T05:18:13.309357Z
false
zendframework/zend-http
https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/src/Header/LastModified.php
src/Header/LastModified.php
<?php /** * @see https://github.com/zendframework/zend-http for the canonical source repository * @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com) * @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License */ namespace Zend\Http\Header; /** * Last-Modified Header * * @link http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.29 */ class LastModified extends AbstractDate { /** * Get header name * * @return string */ public function getFieldName() { return 'Last-Modified'; } }
php
BSD-3-Clause
ac4ffd09d509b2c5c0285178c4f7de740f05c3d9
2026-01-05T05:18:13.309357Z
false
zendframework/zend-http
https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/src/Header/Pragma.php
src/Header/Pragma.php
<?php /** * @see https://github.com/zendframework/zend-http for the canonical source repository * @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com) * @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License */ namespace Zend\Http\Header; /** * @throws Exception\InvalidArgumentException * @see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.32 */ class Pragma implements HeaderInterface { /** * @var string */ protected $value; public static function fromString($headerLine) { list($name, $value) = GenericHeader::splitHeaderLine($headerLine); // check to ensure proper header type for this factory if (strtolower($name) !== 'pragma') { throw new Exception\InvalidArgumentException('Invalid header line for Pragma string: "' . $name . '"'); } // @todo implementation details return new static($value); } public function __construct($value = null) { if ($value !== null) { HeaderValue::assertValid($value); $this->value = $value; } } public function getFieldName() { return 'Pragma'; } public function getFieldValue() { return (string) $this->value; } public function toString() { return 'Pragma: ' . $this->getFieldValue(); } }
php
BSD-3-Clause
ac4ffd09d509b2c5c0285178c4f7de740f05c3d9
2026-01-05T05:18:13.309357Z
false
zendframework/zend-http
https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/src/Header/ContentDisposition.php
src/Header/ContentDisposition.php
<?php /** * @see https://github.com/zendframework/zend-http for the canonical source repository * @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com) * @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License */ namespace Zend\Http\Header; /** * @throws Exception\InvalidArgumentException * @see http://www.w3.org/Protocols/rfc2616/rfc2616-sec19.html#sec19.5.1 */ class ContentDisposition implements HeaderInterface { /** * @var string */ protected $value; public static function fromString($headerLine) { list($name, $value) = GenericHeader::splitHeaderLine($headerLine); // check to ensure proper header type for this factory if (strtolower($name) !== 'content-disposition') { throw new Exception\InvalidArgumentException(sprintf( 'Invalid header line for Content-Disposition string: "%s"', $name )); } // @todo implementation details return new static($value); } public function __construct($value = null) { if ($value !== null) { HeaderValue::assertValid($value); $this->value = $value; } } public function getFieldName() { return 'Content-Disposition'; } public function getFieldValue() { return (string) $this->value; } public function toString() { return 'Content-Disposition: ' . $this->getFieldValue(); } }
php
BSD-3-Clause
ac4ffd09d509b2c5c0285178c4f7de740f05c3d9
2026-01-05T05:18:13.309357Z
false
zendframework/zend-http
https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/src/Header/ContentSecurityPolicy.php
src/Header/ContentSecurityPolicy.php
<?php /** * @see https://github.com/zendframework/zend-http for the canonical source repository * @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com) * @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License */ namespace Zend\Http\Header; /** * Content Security Policy Level 3 Header * * @link http://www.w3.org/TR/CSP/ */ class ContentSecurityPolicy implements MultipleHeaderInterface { /** * Valid directive names * * @var array */ protected $validDirectiveNames = [ // As per http://www.w3.org/TR/CSP/#directives // Fetch directives 'child-src', 'connect-src', 'default-src', 'font-src', 'frame-src', 'img-src', 'manifest-src', 'media-src', 'object-src', 'prefetch-src', 'script-src', 'script-src-elem', 'script-src-attr', 'style-src', 'style-src-elem', 'style-src-attr', 'worker-src', // Document directives 'base-uri', 'plugin-types', 'sandbox', // Navigation directives 'form-action', 'frame-ancestors', 'navigate-to', // Reporting directives 'report-uri', 'report-to', // Other directives 'block-all-mixed-content', 'require-sri-for', 'trusted-types', 'upgrade-insecure-requests', ]; /** * The directives defined for this policy * * @var array */ protected $directives = []; /** * Get the list of defined directives * * @return array */ public function getDirectives() { return $this->directives; } /** * Sets the directive to consist of the source list * * Reverses http://www.w3.org/TR/CSP/#parsing-1 * * @param string $name The directive name. * @param array $sources The source list. * @return $this * @throws Exception\InvalidArgumentException If the name is not a valid directive name. */ public function setDirective($name, array $sources) { if (! in_array($name, $this->validDirectiveNames, true)) { throw new Exception\InvalidArgumentException(sprintf( '%s expects a valid directive name; received "%s"', __METHOD__, (string) $name )); } if ($name === 'block-all-mixed-content' || $name === 'upgrade-insecure-requests' ) { if ($sources) { throw new Exception\InvalidArgumentException(sprintf( 'Received value for %s directive; none expected', $name )); } $this->directives[$name] = ''; return $this; } if (empty($sources)) { if ('report-uri' === $name) { if (isset($this->directives[$name])) { unset($this->directives[$name]); } return $this; } $this->directives[$name] = "'none'"; return $this; } array_walk($sources, [__NAMESPACE__ . '\HeaderValue', 'assertValid']); $this->directives[$name] = implode(' ', $sources); return $this; } /** * Create Content Security Policy header from a given header line * * @param string $headerLine The header line to parse. * @return static * @throws Exception\InvalidArgumentException If the name field in the given header line does not match. */ public static function fromString($headerLine) { $header = new static(); $headerName = $header->getFieldName(); list($name, $value) = GenericHeader::splitHeaderLine($headerLine); // Ensure the proper header name if (strcasecmp($name, $headerName) != 0) { throw new Exception\InvalidArgumentException(sprintf( 'Invalid header line for %s string: "%s"', $headerName, $name )); } // As per http://www.w3.org/TR/CSP/#parsing $tokens = explode(';', $value); foreach ($tokens as $token) { $token = trim($token); if ($token) { list($directiveName, $directiveValue) = array_pad(explode(' ', $token, 2), 2, null); if (! isset($header->directives[$directiveName])) { $header->setDirective( $directiveName, $directiveValue === null ? [] : [$directiveValue] ); } } } return $header; } /** * Get the header name * * @return string */ public function getFieldName() { return 'Content-Security-Policy'; } /** * Get the header value * * @return string */ public function getFieldValue() { $directives = []; foreach ($this->directives as $name => $value) { $directives[] = sprintf('%s %s;', $name, $value); } return str_replace(' ;', ';', implode(' ', $directives)); } /** * Return the header as a string * * @return string */ public function toString() { return sprintf('%s: %s', $this->getFieldName(), $this->getFieldValue()); } public function toStringMultipleHeaders(array $headers) { $strings = [$this->toString()]; foreach ($headers as $header) { if (! $header instanceof ContentSecurityPolicy) { throw new Exception\RuntimeException( 'The ContentSecurityPolicy multiple header implementation can only' . ' accept an array of ContentSecurityPolicy headers' ); } $strings[] = $header->toString(); } return implode("\r\n", $strings) . "\r\n"; } }
php
BSD-3-Clause
ac4ffd09d509b2c5c0285178c4f7de740f05c3d9
2026-01-05T05:18:13.309357Z
false
zendframework/zend-http
https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/src/Header/Via.php
src/Header/Via.php
<?php /** * @see https://github.com/zendframework/zend-http for the canonical source repository * @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com) * @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License */ namespace Zend\Http\Header; /** * @throws Exception\InvalidArgumentException * @see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.45 */ class Via implements HeaderInterface { /** * @var string */ protected $value; public static function fromString($headerLine) { list($name, $value) = GenericHeader::splitHeaderLine($headerLine); // check to ensure proper header type for this factory if (strtolower($name) !== 'via') { throw new Exception\InvalidArgumentException('Invalid header line for Via string: "' . $name . '"'); } // @todo implementation details return new static($value); } public function __construct($value = null) { if ($value !== null) { HeaderValue::assertValid($value); $this->value = $value; } } public function getFieldName() { return 'Via'; } public function getFieldValue() { return (string) $this->value; } public function toString() { return 'Via: ' . $this->getFieldValue(); } }
php
BSD-3-Clause
ac4ffd09d509b2c5c0285178c4f7de740f05c3d9
2026-01-05T05:18:13.309357Z
false
zendframework/zend-http
https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/src/Header/TE.php
src/Header/TE.php
<?php /** * @see https://github.com/zendframework/zend-http for the canonical source repository * @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com) * @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License */ namespace Zend\Http\Header; /** * @throws Exception\InvalidArgumentException * @see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.39 */ class TE implements HeaderInterface { /** * @var string */ protected $value; public static function fromString($headerLine) { list($name, $value) = GenericHeader::splitHeaderLine($headerLine); // check to ensure proper header type for this factory if (strtolower($name) !== 'te') { throw new Exception\InvalidArgumentException('Invalid header line for TE string: "' . $name . '"'); } // @todo implementation details return new static($value); } public function __construct($value = null) { if ($value !== null) { HeaderValue::assertValid($value); $this->value = $value; } } public function getFieldName() { return 'TE'; } public function getFieldValue() { return (string) $this->value; } public function toString() { return 'TE: ' . $this->getFieldValue(); } }
php
BSD-3-Clause
ac4ffd09d509b2c5c0285178c4f7de740f05c3d9
2026-01-05T05:18:13.309357Z
false
zendframework/zend-http
https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/src/Header/ProxyAuthenticate.php
src/Header/ProxyAuthenticate.php
<?php /** * @see https://github.com/zendframework/zend-http for the canonical source repository * @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com) * @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License */ namespace Zend\Http\Header; /** * @throws Exception\InvalidArgumentException * @see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.33 */ class ProxyAuthenticate implements MultipleHeaderInterface { /** * @var string */ protected $value; public static function fromString($headerLine) { list($name, $value) = GenericHeader::splitHeaderLine($headerLine); // check to ensure proper header type for this factory if (strtolower($name) !== 'proxy-authenticate') { throw new Exception\InvalidArgumentException(sprintf( 'Invalid header line for Proxy-Authenticate string: "%s"', $name )); } // @todo implementation details return new static($value); } public function __construct($value = null) { if ($value !== null) { HeaderValue::assertValid($value); $this->value = $value; } } public function getFieldName() { return 'Proxy-Authenticate'; } public function getFieldValue() { return (string) $this->value; } public function toString() { return 'Proxy-Authenticate: ' . $this->getFieldValue(); } public function toStringMultipleHeaders(array $headers) { $strings = [$this->toString()]; foreach ($headers as $header) { if (! $header instanceof ProxyAuthenticate) { throw new Exception\RuntimeException( 'The ProxyAuthenticate multiple header implementation can only accept' . ' an array of ProxyAuthenticate headers' ); } $strings[] = $header->toString(); } return implode("\r\n", $strings); } }
php
BSD-3-Clause
ac4ffd09d509b2c5c0285178c4f7de740f05c3d9
2026-01-05T05:18:13.309357Z
false
zendframework/zend-http
https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/src/Header/Referer.php
src/Header/Referer.php
<?php /** * @see https://github.com/zendframework/zend-http for the canonical source repository * @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com) * @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License */ namespace Zend\Http\Header; use Zend\Uri\Http as HttpUri; /** * Content-Location Header * * @link http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.36 */ class Referer extends AbstractLocation { /** * Set the URI/URL for this header * according to RFC Referer URI should not have fragment * * @param string|HttpUri $uri * @return $this */ public function setUri($uri) { parent::setUri($uri); $this->uri->setFragment(null); return $this; } /** * Return header name * * @return string */ public function getFieldName() { return 'Referer'; } }
php
BSD-3-Clause
ac4ffd09d509b2c5c0285178c4f7de740f05c3d9
2026-01-05T05:18:13.309357Z
false
zendframework/zend-http
https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/src/Header/Date.php
src/Header/Date.php
<?php /** * @see https://github.com/zendframework/zend-http for the canonical source repository * @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com) * @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License */ namespace Zend\Http\Header; /** * Date Header * * @link http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.18 */ class Date extends AbstractDate { /** * Get header name * * @return string */ public function getFieldName() { return 'Date'; } }
php
BSD-3-Clause
ac4ffd09d509b2c5c0285178c4f7de740f05c3d9
2026-01-05T05:18:13.309357Z
false
zendframework/zend-http
https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/src/Header/KeepAlive.php
src/Header/KeepAlive.php
<?php /** * @see https://github.com/zendframework/zend-http for the canonical source repository * @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com) * @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License */ namespace Zend\Http\Header; /** * @throws Exception\InvalidArgumentException * @todo Search for RFC for this header */ class KeepAlive implements HeaderInterface { /** * @var string */ protected $value; public static function fromString($headerLine) { list($name, $value) = GenericHeader::splitHeaderLine($headerLine); // check to ensure proper header type for this factory if (strtolower($name) !== 'keep-alive') { throw new Exception\InvalidArgumentException('Invalid header line for Keep-Alive string: "' . $name . '"'); } // @todo implementation details return new static($value); } public function __construct($value = null) { if ($value !== null) { HeaderValue::assertValid($value); $this->value = $value; } } public function getFieldName() { return 'Keep-Alive'; } public function getFieldValue() { return (string) $this->value; } public function toString() { return 'Keep-Alive: ' . $this->getFieldValue(); } }
php
BSD-3-Clause
ac4ffd09d509b2c5c0285178c4f7de740f05c3d9
2026-01-05T05:18:13.309357Z
false
zendframework/zend-http
https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/src/Header/From.php
src/Header/From.php
<?php /** * @see https://github.com/zendframework/zend-http for the canonical source repository * @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com) * @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License */ namespace Zend\Http\Header; /** * @throws Exception\InvalidArgumentException * @see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.22 */ class From implements HeaderInterface { /** * @var string */ protected $value; public static function fromString($headerLine) { list($name, $value) = GenericHeader::splitHeaderLine($headerLine); // check to ensure proper header type for this factory if (strtolower($name) !== 'from') { throw new Exception\InvalidArgumentException('Invalid header line for From string: "' . $name . '"'); } // @todo implementation details return new static($value); } public function __construct($value = null) { if ($value !== null) { HeaderValue::assertValid($value); $this->value = $value; } } public function getFieldName() { return 'From'; } public function getFieldValue() { return (string) $this->value; } public function toString() { return 'From: ' . $this->getFieldValue(); } }
php
BSD-3-Clause
ac4ffd09d509b2c5c0285178c4f7de740f05c3d9
2026-01-05T05:18:13.309357Z
false
zendframework/zend-http
https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/src/Header/Origin.php
src/Header/Origin.php
<?php /** * @see https://github.com/zendframework/zend-http for the canonical source repository * @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com) * @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License */ namespace Zend\Http\Header; use Zend\Uri\UriFactory; /** * @throws Exception\InvalidArgumentException * @see http://tools.ietf.org/id/draft-abarth-origin-03.html#rfc.section.2 */ class Origin implements HeaderInterface { /** * @var string */ protected $value = ''; public static function fromString($headerLine) { list($name, $value) = explode(': ', $headerLine, 2); // check to ensure proper header type for this factory if (strtolower($name) !== 'origin') { throw new Exception\InvalidArgumentException('Invalid header line for Origin string: "' . $name . '"'); } $uri = UriFactory::factory($value); if (! $uri->isValid()) { throw new Exception\InvalidArgumentException('Invalid header value for Origin key: "' . $name . '"'); } return new static($value); } /** * @param string|null $value */ public function __construct($value = null) { if ($value !== null) { HeaderValue::assertValid($value); $this->value = $value; } } public function getFieldName() { return 'Origin'; } public function getFieldValue() { return (string) $this->value; } public function toString() { return 'Origin: ' . $this->getFieldValue(); } }
php
BSD-3-Clause
ac4ffd09d509b2c5c0285178c4f7de740f05c3d9
2026-01-05T05:18:13.309357Z
false
zendframework/zend-http
https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/src/Header/Upgrade.php
src/Header/Upgrade.php
<?php /** * @see https://github.com/zendframework/zend-http for the canonical source repository * @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com) * @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License */ namespace Zend\Http\Header; /** * @throws Exception\InvalidArgumentException * @see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.42 */ class Upgrade implements HeaderInterface { /** * @var string */ protected $value; public static function fromString($headerLine) { list($name, $value) = GenericHeader::splitHeaderLine($headerLine); // check to ensure proper header type for this factory if (strtolower($name) !== 'upgrade') { throw new Exception\InvalidArgumentException('Invalid header line for Upgrade string: "' . $name . '"'); } // @todo implementation details return new static($value); } public function __construct($value = null) { if ($value !== null) { HeaderValue::assertValid($value); $this->value = $value; } } public function getFieldName() { return 'Upgrade'; } public function getFieldValue() { return (string) $this->value; } public function toString() { return 'Upgrade: ' . $this->getFieldValue(); } }
php
BSD-3-Clause
ac4ffd09d509b2c5c0285178c4f7de740f05c3d9
2026-01-05T05:18:13.309357Z
false
zendframework/zend-http
https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/src/Header/Range.php
src/Header/Range.php
<?php /** * @see https://github.com/zendframework/zend-http for the canonical source repository * @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com) * @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License */ namespace Zend\Http\Header; /** * @throws Exception\InvalidArgumentException * @see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35.2 */ class Range implements HeaderInterface { /** * @var string */ protected $value; public static function fromString($headerLine) { list($name, $value) = GenericHeader::splitHeaderLine($headerLine); // check to ensure proper header type for this factory if (strtolower($name) !== 'range') { throw new Exception\InvalidArgumentException('Invalid header line for Range string: "' . $name . '"'); } // @todo implementation details return new static($value); } public function __construct($value = null) { if ($value !== null) { HeaderValue::assertValid($value); $this->value = $value; } } public function getFieldName() { return 'Range'; } public function getFieldValue() { return (string) $this->value; } public function toString() { return 'Range: ' . $this->getFieldValue(); } }
php
BSD-3-Clause
ac4ffd09d509b2c5c0285178c4f7de740f05c3d9
2026-01-05T05:18:13.309357Z
false
zendframework/zend-http
https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/src/Header/ContentLanguage.php
src/Header/ContentLanguage.php
<?php /** * @see https://github.com/zendframework/zend-http for the canonical source repository * @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com) * @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License */ namespace Zend\Http\Header; /** * @throws Exception\InvalidArgumentException * @see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.12 */ class ContentLanguage implements HeaderInterface { /** * @var string */ protected $value; public static function fromString($headerLine) { list($name, $value) = GenericHeader::splitHeaderLine($headerLine); // check to ensure proper header type for this factory if (strtolower($name) !== 'content-language') { throw new Exception\InvalidArgumentException(sprintf( 'Invalid header line for Content-Language string: "%s"', $name )); } // @todo implementation details return new static($value); } public function __construct($value = null) { if ($value !== null) { HeaderValue::assertValid($value); $this->value = $value; } } public function getFieldName() { return 'Content-Language'; } public function getFieldValue() { return (string) $this->value; } public function toString() { return 'Content-Language: ' . $this->getFieldValue(); } }
php
BSD-3-Clause
ac4ffd09d509b2c5c0285178c4f7de740f05c3d9
2026-01-05T05:18:13.309357Z
false
zendframework/zend-http
https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/src/Header/GenericMultiHeader.php
src/Header/GenericMultiHeader.php
<?php /** * @see https://github.com/zendframework/zend-http for the canonical source repository * @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com) * @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License */ namespace Zend\Http\Header; class GenericMultiHeader extends GenericHeader implements MultipleHeaderInterface { public static function fromString($headerLine) { list($fieldName, $fieldValue) = GenericHeader::splitHeaderLine($headerLine); if (strpos($fieldValue, ',')) { $headers = []; foreach (explode(',', $fieldValue) as $multiValue) { $headers[] = new static($fieldName, $multiValue); } return $headers; } else { $header = new static($fieldName, $fieldValue); return $header; } } public function toStringMultipleHeaders(array $headers) { $name = $this->getFieldName(); $values = [$this->getFieldValue()]; foreach ($headers as $header) { if (! $header instanceof static) { throw new Exception\InvalidArgumentException( 'This method toStringMultipleHeaders was expecting an array of headers of the same type' ); } $values[] = $header->getFieldValue(); } return $name . ': ' . implode(',', $values) . "\r\n"; } }
php
BSD-3-Clause
ac4ffd09d509b2c5c0285178c4f7de740f05c3d9
2026-01-05T05:18:13.309357Z
false
zendframework/zend-http
https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/src/Header/IfNoneMatch.php
src/Header/IfNoneMatch.php
<?php /** * @see https://github.com/zendframework/zend-http for the canonical source repository * @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com) * @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License */ namespace Zend\Http\Header; /** * @throws Exception\InvalidArgumentException * @see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.26 */ class IfNoneMatch implements HeaderInterface { /** * @var string */ protected $value; public static function fromString($headerLine) { list($name, $value) = GenericHeader::splitHeaderLine($headerLine); // check to ensure proper header type for this factory if (strtolower($name) !== 'if-none-match') { throw new Exception\InvalidArgumentException(sprintf( 'Invalid header line for If-None-Match string: "%s"', $name )); } // @todo implementation details return new static($value); } public function __construct($value = null) { if ($value !== null) { HeaderValue::assertValid($value); $this->value = $value; } } public function getFieldName() { return 'If-None-Match'; } public function getFieldValue() { return (string) $this->value; } public function toString() { return 'If-None-Match: ' . $this->getFieldValue(); } }
php
BSD-3-Clause
ac4ffd09d509b2c5c0285178c4f7de740f05c3d9
2026-01-05T05:18:13.309357Z
false
zendframework/zend-http
https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/src/Header/AuthenticationInfo.php
src/Header/AuthenticationInfo.php
<?php /** * @see https://github.com/zendframework/zend-http for the canonical source repository * @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com) * @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License */ namespace Zend\Http\Header; /** * @throws Exception\InvalidArgumentException * @see http://www.ietf.org/rfc/rfc2617.txt */ class AuthenticationInfo implements HeaderInterface { /** * @var string */ protected $value; public static function fromString($headerLine) { list($name, $value) = GenericHeader::splitHeaderLine($headerLine); // check to ensure proper header type for this factory if (strtolower($name) !== 'authentication-info') { throw new Exception\InvalidArgumentException(sprintf( 'Invalid header line for Authentication-Info string: "%s"', $name )); } // @todo implementation details return new static($value); } public function __construct($value = null) { if ($value !== null) { HeaderValue::assertValid($value); $this->value = $value; } } public function getFieldName() { return 'Authentication-Info'; } public function getFieldValue() { return (string) $this->value; } public function toString() { return 'Authentication-Info: ' . $this->getFieldValue(); } }
php
BSD-3-Clause
ac4ffd09d509b2c5c0285178c4f7de740f05c3d9
2026-01-05T05:18:13.309357Z
false
zendframework/zend-http
https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/src/Header/IfModifiedSince.php
src/Header/IfModifiedSince.php
<?php /** * @see https://github.com/zendframework/zend-http for the canonical source repository * @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com) * @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License */ namespace Zend\Http\Header; /** * If-Modified-Since Header * * @link http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.25 */ class IfModifiedSince extends AbstractDate { /** * Get header name * * @return string */ public function getFieldName() { return 'If-Modified-Since'; } }
php
BSD-3-Clause
ac4ffd09d509b2c5c0285178c4f7de740f05c3d9
2026-01-05T05:18:13.309357Z
false
zendframework/zend-http
https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/src/Header/WWWAuthenticate.php
src/Header/WWWAuthenticate.php
<?php /** * @see https://github.com/zendframework/zend-http for the canonical source repository * @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com) * @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License */ namespace Zend\Http\Header; /** * @throws Exception\InvalidArgumentException * @see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.47 */ class WWWAuthenticate implements MultipleHeaderInterface { /** * @var string */ protected $value; public static function fromString($headerLine) { list($name, $value) = GenericHeader::splitHeaderLine($headerLine); // check to ensure proper header type for this factory if (strtolower($name) !== 'www-authenticate') { throw new Exception\InvalidArgumentException(sprintf( 'Invalid header line for WWW-Authenticate string: "%s"', $name )); } // @todo implementation details return new static($value); } public function __construct($value = null) { if ($value !== null) { HeaderValue::assertValid($value); $this->value = $value; } } public function getFieldName() { return 'WWW-Authenticate'; } public function getFieldValue() { return (string) $this->value; } public function toString() { return 'WWW-Authenticate: ' . $this->getFieldValue(); } public function toStringMultipleHeaders(array $headers) { $strings = [$this->toString()]; foreach ($headers as $header) { if (! $header instanceof WWWAuthenticate) { throw new Exception\RuntimeException( 'The WWWAuthenticate multiple header implementation can only' . ' accept an array of WWWAuthenticate headers' ); } $strings[] = $header->toString(); } return implode("\r\n", $strings); } }
php
BSD-3-Clause
ac4ffd09d509b2c5c0285178c4f7de740f05c3d9
2026-01-05T05:18:13.309357Z
false
zendframework/zend-http
https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/src/Header/IfUnmodifiedSince.php
src/Header/IfUnmodifiedSince.php
<?php /** * @see https://github.com/zendframework/zend-http for the canonical source repository * @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com) * @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License */ namespace Zend\Http\Header; /** * If-Unmodified-Since Header * * @link http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.28 */ class IfUnmodifiedSince extends AbstractDate { /** * Get header name * * @return string */ public function getFieldName() { return 'If-Unmodified-Since'; } }
php
BSD-3-Clause
ac4ffd09d509b2c5c0285178c4f7de740f05c3d9
2026-01-05T05:18:13.309357Z
false
zendframework/zend-http
https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/src/Header/AbstractLocation.php
src/Header/AbstractLocation.php
<?php /** * @see https://github.com/zendframework/zend-http for the canonical source repository * @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com) * @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License */ namespace Zend\Http\Header; use Zend\Uri\Exception as UriException; use Zend\Uri\UriFactory; use Zend\Uri\UriInterface; /** * Abstract Location Header * Supports headers that have URI as value * @see Zend\Http\Header\Location * @see Zend\Http\Header\ContentLocation * @see Zend\Http\Header\Referer * * Note for 'Location' header: * While RFC 1945 requires an absolute URI, most of the browsers also support relative URI * This class allows relative URIs, and let user retrieve URI instance if strict validation needed */ abstract class AbstractLocation implements HeaderInterface { /** * URI for this header * * @var UriInterface */ protected $uri; /** * Create location-based header from string * * @param string $headerLine * @return static * @throws Exception\InvalidArgumentException */ public static function fromString($headerLine) { $locationHeader = new static(); // ZF-5520 - IIS bug, no space after colon list($name, $uri) = GenericHeader::splitHeaderLine($headerLine); // check to ensure proper header type for this factory if (strtolower($name) !== strtolower($locationHeader->getFieldName())) { throw new Exception\InvalidArgumentException( 'Invalid header line for "' . $locationHeader->getFieldName() . '" header string' ); } HeaderValue::assertValid($uri); $locationHeader->setUri(trim($uri)); return $locationHeader; } /** * Set the URI/URL for this header, this can be a string or an instance of Zend\Uri\Http * * @param string|UriInterface $uri * @return $this * @throws Exception\InvalidArgumentException */ public function setUri($uri) { if (is_string($uri)) { try { $uri = UriFactory::factory($uri); } catch (UriException\InvalidUriPartException $e) { throw new Exception\InvalidArgumentException( sprintf('Invalid URI passed as string (%s)', (string) $uri), $e->getCode(), $e ); } catch (UriException\InvalidArgumentException $e) { throw new Exception\InvalidArgumentException( sprintf('Invalid URI passed as string (%s)', (string) $uri), $e->getCode(), $e ); } } elseif (! ($uri instanceof UriInterface)) { throw new Exception\InvalidArgumentException('URI must be an instance of Zend\Uri\Http or a string'); } $this->uri = $uri; return $this; } /** * Return the URI for this header * * @return string */ public function getUri() { if ($this->uri instanceof UriInterface) { return $this->uri->toString(); } return $this->uri; } /** * Return the URI for this header as an instance of Zend\Uri\Http * * @return UriInterface */ public function uri() { if ($this->uri === null || is_string($this->uri)) { $this->uri = UriFactory::factory($this->uri); } return $this->uri; } /** * Get header value as URI string * * @return string */ public function getFieldValue() { return $this->getUri(); } /** * Output header line * * @return string */ public function toString() { return $this->getFieldName() . ': ' . $this->getUri(); } /** * Allow casting to string * * @return string */ public function __toString() { return $this->toString(); } }
php
BSD-3-Clause
ac4ffd09d509b2c5c0285178c4f7de740f05c3d9
2026-01-05T05:18:13.309357Z
false
zendframework/zend-http
https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/src/Header/AbstractDate.php
src/Header/AbstractDate.php
<?php /** * @see https://github.com/zendframework/zend-http for the canonical source repository * @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com) * @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License */ namespace Zend\Http\Header; use DateTime; use DateTimeZone; /** * Abstract Date/Time Header * Supports headers that have date/time as value * * @see Zend\Http\Header\Date * @see Zend\Http\Header\Expires * @see Zend\Http\Header\IfModifiedSince * @see Zend\Http\Header\IfUnmodifiedSince * @see Zend\Http\Header\LastModified * * Note for 'Location' header: * While RFC 1945 requires an absolute URI, most of the browsers also support relative URI * This class allows relative URIs, and let user retrieve URI instance if strict validation needed */ abstract class AbstractDate implements HeaderInterface { /** * Date formats according to RFC 2616 * @link http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3 */ const DATE_RFC1123 = 0; const DATE_RFC1036 = 1; const DATE_ANSIC = 2; /** * Date instance for this header * * @var DateTime */ protected $date; /** * Date output format * * @var string */ protected static $dateFormat = 'D, d M Y H:i:s \G\M\T'; /** * Date formats defined by RFC 2616. RFC 1123 date is required * RFC 1036 and ANSI C formats are provided for compatibility with old servers/clients * @link http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3 * * @var array */ protected static $dateFormats = [ self::DATE_RFC1123 => 'D, d M Y H:i:s \G\M\T', self::DATE_RFC1036 => 'D, d M y H:i:s \G\M\T', self::DATE_ANSIC => 'D M j H:i:s Y', ]; /** * Create date-based header from string * * @param string $headerLine * @return static * @throws Exception\InvalidArgumentException */ public static function fromString($headerLine) { $dateHeader = new static(); list($name, $date) = GenericHeader::splitHeaderLine($headerLine); // check to ensure proper header type for this factory if (strtolower($name) !== strtolower($dateHeader->getFieldName())) { throw new Exception\InvalidArgumentException( 'Invalid header line for "' . $dateHeader->getFieldName() . '" header string' ); } $dateHeader->setDate($date); return $dateHeader; } /** * Create date-based header from strtotime()-compatible string * * @param int|string $time * @return static * @throws Exception\InvalidArgumentException */ public static function fromTimeString($time) { return static::fromTimestamp(strtotime($time)); } /** * Create date-based header from Unix timestamp * * @param int $time * @return static * @throws Exception\InvalidArgumentException */ public static function fromTimestamp($time) { $dateHeader = new static(); if (! $time || ! is_numeric($time)) { throw new Exception\InvalidArgumentException( 'Invalid time for "' . $dateHeader->getFieldName() . '" header string' ); } $dateHeader->setDate(new DateTime('@' . $time)); return $dateHeader; } /** * Set date output format * * @param int $format * @throws Exception\InvalidArgumentException */ public static function setDateFormat($format) { if (! isset(static::$dateFormats[$format])) { throw new Exception\InvalidArgumentException(sprintf( 'No constant defined for provided date format: %s', $format )); } static::$dateFormat = static::$dateFormats[$format]; } /** * Return current date output format * * @return string */ public static function getDateFormat() { return static::$dateFormat; } /** * Set the date for this header, this can be a string or an instance of \DateTime * * @param string|DateTime $date * @return $this * @throws Exception\InvalidArgumentException */ public function setDate($date) { if (is_string($date)) { try { $date = new DateTime($date, new DateTimeZone('GMT')); } catch (\Exception $e) { throw new Exception\InvalidArgumentException( sprintf('Invalid date passed as string (%s)', (string) $date), $e->getCode(), $e ); } } elseif (! ($date instanceof DateTime)) { throw new Exception\InvalidArgumentException('Date must be an instance of \DateTime or a string'); } $date->setTimezone(new DateTimeZone('GMT')); $this->date = $date; return $this; } /** * Return date for this header * * @return string */ public function getDate() { return $this->date()->format(static::$dateFormat); } /** * Return date for this header as an instance of \DateTime * * @return DateTime */ public function date() { if ($this->date === null) { $this->date = new DateTime(null, new DateTimeZone('GMT')); } return $this->date; } /** * Compare provided date to date for this header * Returns < 0 if date in header is less than $date; > 0 if it's greater, and 0 if they are equal. * @see \strcmp() * * @param string|DateTime $date * @return int * @throws Exception\InvalidArgumentException */ public function compareTo($date) { if (is_string($date)) { try { $date = new DateTime($date, new DateTimeZone('GMT')); } catch (\Exception $e) { throw new Exception\InvalidArgumentException( sprintf('Invalid Date passed as string (%s)', (string) $date), $e->getCode(), $e ); } } elseif (! ($date instanceof DateTime)) { throw new Exception\InvalidArgumentException('Date must be an instance of \DateTime or a string'); } $dateTimestamp = $date->getTimestamp(); $thisTimestamp = $this->date()->getTimestamp(); return ($thisTimestamp === $dateTimestamp) ? 0 : (($thisTimestamp > $dateTimestamp) ? 1 : -1); } /** * Get header value as formatted date * * @return string */ public function getFieldValue() { return $this->getDate(); } /** * Return header line * * @return string */ public function toString() { return $this->getFieldName() . ': ' . $this->getDate(); } /** * Allow casting to string * * @return string */ public function __toString() { return $this->toString(); } }
php
BSD-3-Clause
ac4ffd09d509b2c5c0285178c4f7de740f05c3d9
2026-01-05T05:18:13.309357Z
false
zendframework/zend-http
https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/src/Header/FeaturePolicy.php
src/Header/FeaturePolicy.php
<?php /** * @see https://github.com/zendframework/zend-http for the canonical source repository * @copyright Copyright (c) 2019 Zend Technologies USA Inc. (https://www.zend.com) * @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License */ namespace Zend\Http\Header; /** * Feature Policy (based on Editor’s Draft, 28 November 2019) * * @link https://w3c.github.io/webappsec-feature-policy/ */ class FeaturePolicy implements HeaderInterface { /** * Valid directive names * * @var string[] * * @see https://github.com/w3c/webappsec-feature-policy/blob/master/features.md */ protected $validDirectiveNames = [ // Standardized Features 'accelerometer', 'ambient-light-sensor', 'autoplay', 'battery', 'camera', 'display-capture', 'document-domain', 'fullscreen', 'execution-while-not-rendered', 'execution-while-out-of-viewport', 'gyroscope', 'magnetometer', 'microphone', 'midi', 'payment', 'picture-in-picture', 'sync-xhr', 'usb', 'wake-lock', 'xr', // Proposed Features 'encrypted-media', 'geolocation', 'speaker', // Experimental Features 'document-write', 'font-display-late-swap', 'layout-animations', 'loading-frame-default-eager', 'loading-image-default-eager', 'legacy-image-formats', 'oversized-images', 'sync-script', 'unoptimized-lossy-images', 'unoptimized-lossless-images', 'unsized-media', 'vertical-scroll', 'serial', ]; /** * The directives defined for this policy * * @var array */ protected $directives = []; /** * Get the list of defined directives * * @return array */ public function getDirectives() { return $this->directives; } /** * Sets the directive to consist of the source list * * @param string $name The directive name. * @param string[] $sources The source list. * @return $this * @throws Exception\InvalidArgumentException If the name is not a valid directive name. */ public function setDirective($name, array $sources) { if (! in_array($name, $this->validDirectiveNames, true)) { throw new Exception\InvalidArgumentException(sprintf( '%s expects a valid directive name; received "%s"', __METHOD__, (string) $name )); } if (empty($sources)) { $this->directives[$name] = "'none'"; return $this; } array_walk($sources, [__NAMESPACE__ . '\HeaderValue', 'assertValid']); $this->directives[$name] = implode(' ', $sources); return $this; } /** * Create Feature Policy header from a given header line * * @param string $headerLine The header line to parse. * @return static * @throws Exception\InvalidArgumentException If the name field in the given header line does not match. */ public static function fromString($headerLine) { $header = new static(); $headerName = $header->getFieldName(); list($name, $value) = GenericHeader::splitHeaderLine($headerLine); // Ensure the proper header name if (strcasecmp($name, $headerName) !== 0) { throw new Exception\InvalidArgumentException(sprintf( 'Invalid header line for %s string: "%s"', $headerName, $name )); } // As per https://w3c.github.io/webappsec-feature-policy/#algo-parse-policy-directive $tokens = explode(';', $value); foreach ($tokens as $token) { $token = trim($token); if ($token) { list($directiveName, $directiveValue) = array_pad(explode(' ', $token, 2), 2, null); if (! isset($header->directives[$directiveName])) { $header->setDirective( $directiveName, $directiveValue === null ? [] : [$directiveValue] ); } } } return $header; } /** * Get the header name * * @return string */ public function getFieldName() { return 'Feature-Policy'; } /** * Get the header value * * @return string */ public function getFieldValue() { $directives = []; foreach ($this->directives as $name => $value) { $directives[] = sprintf('%s %s;', $name, $value); } return implode(' ', $directives); } /** * Return the header as a string * * @return string */ public function toString() { return sprintf('%s: %s', $this->getFieldName(), $this->getFieldValue()); } }
php
BSD-3-Clause
ac4ffd09d509b2c5c0285178c4f7de740f05c3d9
2026-01-05T05:18:13.309357Z
false
zendframework/zend-http
https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/src/Header/Vary.php
src/Header/Vary.php
<?php /** * @see https://github.com/zendframework/zend-http for the canonical source repository * @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com) * @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License */ namespace Zend\Http\Header; /** * @throws Exception\InvalidArgumentException * @see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.44 */ class Vary implements HeaderInterface { /** * @var string */ protected $value; public static function fromString($headerLine) { list($name, $value) = GenericHeader::splitHeaderLine($headerLine); // check to ensure proper header type for this factory if (strtolower($name) !== 'vary') { throw new Exception\InvalidArgumentException('Invalid header line for Vary string: "' . $name . '"'); } // @todo implementation details return new static($value); } public function __construct($value = null) { if ($value !== null) { HeaderValue::assertValid($value); $this->value = $value; } } public function getFieldName() { return 'Vary'; } public function getFieldValue() { return (string) $this->value; } public function toString() { return 'Vary: ' . $this->getFieldValue(); } }
php
BSD-3-Clause
ac4ffd09d509b2c5c0285178c4f7de740f05c3d9
2026-01-05T05:18:13.309357Z
false
zendframework/zend-http
https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/src/Header/IfMatch.php
src/Header/IfMatch.php
<?php /** * @see https://github.com/zendframework/zend-http for the canonical source repository * @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com) * @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License */ namespace Zend\Http\Header; /** * @throws Exception\InvalidArgumentException * @see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.24 */ class IfMatch implements HeaderInterface { /** * @var string */ protected $value; public static function fromString($headerLine) { list($name, $value) = GenericHeader::splitHeaderLine($headerLine); // check to ensure proper header type for this factory if (strtolower($name) !== 'if-match') { throw new Exception\InvalidArgumentException('Invalid header line for If-Match string: "' . $name . '"'); } // @todo implementation details return new static($value); } public function __construct($value = null) { if ($value !== null) { HeaderValue::assertValid($value); $this->value = $value; } } public function getFieldName() { return 'If-Match'; } public function getFieldValue() { return (string) $this->value; } public function toString() { return 'If-Match: ' . $this->getFieldValue(); } }
php
BSD-3-Clause
ac4ffd09d509b2c5c0285178c4f7de740f05c3d9
2026-01-05T05:18:13.309357Z
false
zendframework/zend-http
https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/src/Header/Location.php
src/Header/Location.php
<?php /** * @see https://github.com/zendframework/zend-http for the canonical source repository * @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com) * @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License */ namespace Zend\Http\Header; /** * Location Header * * @link http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.30 */ class Location extends AbstractLocation { /** * Return header name * * @return string */ public function getFieldName() { return 'Location'; } }
php
BSD-3-Clause
ac4ffd09d509b2c5c0285178c4f7de740f05c3d9
2026-01-05T05:18:13.309357Z
false
zendframework/zend-http
https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/src/Header/Server.php
src/Header/Server.php
<?php /** * @see https://github.com/zendframework/zend-http for the canonical source repository * @copyright Copyright (c) 2005-2019 Zend Technologies USA Inc. (http://www.zend.com) * @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License */ namespace Zend\Http\Header; /** * @throws Exception\InvalidArgumentException * @see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.38 */ class Server implements HeaderInterface { /** * @var string */ protected $value; public static function fromString($headerLine) { list($name, $value) = GenericHeader::splitHeaderLine($headerLine); // check to ensure proper header type for this factory if (strtolower($name) !== 'server') { throw new Exception\InvalidArgumentException('Invalid header line for Server string: "' . $name . '"'); } // @todo implementation details return new static($value); } public function __construct($value = null) { if ($value !== null) { HeaderValue::assertValid($value); $this->value = $value; } } public function getFieldName() { return 'Server'; } public function getFieldValue() { return (string) $this->value; } public function toString() { return 'Server: ' . $this->getFieldValue(); } }
php
BSD-3-Clause
ac4ffd09d509b2c5c0285178c4f7de740f05c3d9
2026-01-05T05:18:13.309357Z
false
zendframework/zend-http
https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/src/Header/IfRange.php
src/Header/IfRange.php
<?php /** * @see https://github.com/zendframework/zend-http for the canonical source repository * @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com) * @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License */ namespace Zend\Http\Header; /** * @throws Exception\InvalidArgumentException * @see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.27 */ class IfRange implements HeaderInterface { /** * @var string */ protected $value; public static function fromString($headerLine) { list($name, $value) = GenericHeader::splitHeaderLine($headerLine); // check to ensure proper header type for this factory if (strtolower($name) !== 'if-range') { throw new Exception\InvalidArgumentException('Invalid header line for If-Range string: "' . $name . '"'); } // @todo implementation details return new static($value); } public function __construct($value = null) { if ($value !== null) { HeaderValue::assertValid($value); $this->value = $value; } } public function getFieldName() { return 'If-Range'; } public function getFieldValue() { return (string) $this->value; } public function toString() { return 'If-Range: ' . $this->getFieldValue(); } }
php
BSD-3-Clause
ac4ffd09d509b2c5c0285178c4f7de740f05c3d9
2026-01-05T05:18:13.309357Z
false
zendframework/zend-http
https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/src/Header/ProxyAuthorization.php
src/Header/ProxyAuthorization.php
<?php /** * @see https://github.com/zendframework/zend-http for the canonical source repository * @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com) * @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License */ namespace Zend\Http\Header; /** * @throws Exception\InvalidArgumentException * @see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.34 */ class ProxyAuthorization implements HeaderInterface { /** * @var string */ protected $value; public static function fromString($headerLine) { list($name, $value) = GenericHeader::splitHeaderLine($headerLine); // check to ensure proper header type for this factory if (strtolower($name) !== 'proxy-authorization') { throw new Exception\InvalidArgumentException(sprintf( 'Invalid header line for Proxy-Authorization string: "%s"', $name )); } // @todo implementation details return new static($value); } public function __construct($value = null) { if ($value !== null) { HeaderValue::assertValid($value); $this->value = $value; } } public function getFieldName() { return 'Proxy-Authorization'; } public function getFieldValue() { return (string) $this->value; } public function toString() { return 'Proxy-Authorization: ' . $this->getFieldValue(); } }
php
BSD-3-Clause
ac4ffd09d509b2c5c0285178c4f7de740f05c3d9
2026-01-05T05:18:13.309357Z
false
zendframework/zend-http
https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/src/Header/ContentTransferEncoding.php
src/Header/ContentTransferEncoding.php
<?php /** * @see https://github.com/zendframework/zend-http for the canonical source repository * @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com) * @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License */ namespace Zend\Http\Header; /** * @throws Exception\InvalidArgumentException * @see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.11 @todo find section */ class ContentTransferEncoding implements HeaderInterface { /** * @var string */ protected $value; public static function fromString($headerLine) { list($name, $value) = GenericHeader::splitHeaderLine($headerLine); // check to ensure proper header type for this factory if (strtolower($name) !== 'content-transfer-encoding') { throw new Exception\InvalidArgumentException(sprintf( 'Invalid header line for Content-Transfer-Encoding string: "%s"', $name )); } // @todo implementation details return new static(strtolower($value)); } public function __construct($value = null) { if ($value !== null) { HeaderValue::assertValid($value); $this->value = $value; } } public function getFieldName() { return 'Content-Transfer-Encoding'; } public function getFieldValue() { return (string) $this->value; } public function toString() { return 'Content-Transfer-Encoding: ' . $this->getFieldValue(); } }
php
BSD-3-Clause
ac4ffd09d509b2c5c0285178c4f7de740f05c3d9
2026-01-05T05:18:13.309357Z
false
zendframework/zend-http
https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/src/Header/Cookie.php
src/Header/Cookie.php
<?php /** * @see https://github.com/zendframework/zend-http for the canonical source repository * @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com) * @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License */ namespace Zend\Http\Header; use ArrayObject; /** * @see http://www.ietf.org/rfc/rfc2109.txt * @see http://www.w3.org/Protocols/rfc2109/rfc2109 */ class Cookie extends ArrayObject implements HeaderInterface { protected $encodeValue = true; public static function fromSetCookieArray(array $setCookies) { $nvPairs = []; foreach ($setCookies as $setCookie) { if (! $setCookie instanceof SetCookie) { throw new Exception\InvalidArgumentException(sprintf( '%s requires an array of SetCookie objects', __METHOD__ )); } if (array_key_exists($setCookie->getName(), $nvPairs)) { throw new Exception\InvalidArgumentException(sprintf( 'Two cookies with the same name were provided to %s', __METHOD__ )); } $nvPairs[$setCookie->getName()] = $setCookie->getValue(); } return new static($nvPairs); } public static function fromString($headerLine) { $header = new static(); list($name, $value) = GenericHeader::splitHeaderLine($headerLine); // check to ensure proper header type for this factory if (strtolower($name) !== 'cookie') { throw new Exception\InvalidArgumentException('Invalid header line for Server string: "' . $name . '"'); } $nvPairs = preg_split('#;\s*#', $value); $arrayInfo = []; foreach ($nvPairs as $nvPair) { $parts = explode('=', $nvPair, 2); if (count($parts) != 2) { throw new Exception\RuntimeException('Malformed Cookie header found'); } list($name, $value) = $parts; $arrayInfo[$name] = urldecode($value); } $header->exchangeArray($arrayInfo); return $header; } public function __construct(array $array = []) { parent::__construct($array, ArrayObject::ARRAY_AS_PROPS); } /** * @param bool $encodeValue * * @return $this */ public function setEncodeValue($encodeValue) { $this->encodeValue = (bool) $encodeValue; return $this; } /** * @return bool */ public function getEncodeValue() { return $this->encodeValue; } public function getFieldName() { return 'Cookie'; } public function getFieldValue() { $nvPairs = []; foreach ($this->flattenCookies($this) as $name => $value) { $nvPairs[] = $name . '=' . (($this->encodeValue) ? urlencode($value) : $value); } return implode('; ', $nvPairs); } protected function flattenCookies($data, $prefix = null) { $result = []; foreach ($data as $key => $value) { $key = $prefix ? $prefix . '[' . $key . ']' : $key; if (is_array($value)) { $result = array_merge($result, $this->flattenCookies($value, $key)); } else { $result[$key] = $value; } } return $result; } public function toString() { return 'Cookie: ' . $this->getFieldValue(); } /** * Get the cookie as a string, suitable for sending as a "Cookie" header in an * HTTP request * * @return string */ public function __toString() { return $this->toString(); } }
php
BSD-3-Clause
ac4ffd09d509b2c5c0285178c4f7de740f05c3d9
2026-01-05T05:18:13.309357Z
false
zendframework/zend-http
https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/src/Header/Expect.php
src/Header/Expect.php
<?php /** * @see https://github.com/zendframework/zend-http for the canonical source repository * @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com) * @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License */ namespace Zend\Http\Header; /** * @throws Exception\InvalidArgumentException * @see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.20 */ class Expect implements HeaderInterface { /** * @var string */ protected $value; public static function fromString($headerLine) { list($name, $value) = GenericHeader::splitHeaderLine($headerLine); // check to ensure proper header type for this factory if (strtolower($name) !== 'expect') { throw new Exception\InvalidArgumentException('Invalid header line for Expect string: "' . $name . '"'); } // @todo implementation details return new static($value); } public function __construct($value = null) { if ($value !== null) { HeaderValue::assertValid($value); $this->value = $value; } } public function getFieldName() { return 'Expect'; } public function getFieldValue() { return (string) $this->value; } public function toString() { return 'Expect: ' . $this->getFieldValue(); } }
php
BSD-3-Clause
ac4ffd09d509b2c5c0285178c4f7de740f05c3d9
2026-01-05T05:18:13.309357Z
false
zendframework/zend-http
https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/src/Header/Warning.php
src/Header/Warning.php
<?php /** * @see https://github.com/zendframework/zend-http for the canonical source repository * @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com) * @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License */ namespace Zend\Http\Header; /** * @throws Exception\InvalidArgumentException * @see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.46 */ class Warning implements HeaderInterface { /** * @var string */ protected $value; public static function fromString($headerLine) { list($name, $value) = GenericHeader::splitHeaderLine($headerLine); // check to ensure proper header type for this factory if (strtolower($name) !== 'warning') { throw new Exception\InvalidArgumentException('Invalid header line for Warning string: "' . $name . '"'); } // @todo implementation details return new static($value); } public function __construct($value = null) { if ($value !== null) { HeaderValue::assertValid($value); $this->value = $value; } } public function getFieldName() { return 'Warning'; } public function getFieldValue() { return (string) $this->value; } public function toString() { return 'Warning: ' . $this->getFieldValue(); } }
php
BSD-3-Clause
ac4ffd09d509b2c5c0285178c4f7de740f05c3d9
2026-01-05T05:18:13.309357Z
false
zendframework/zend-http
https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/src/Header/ContentMD5.php
src/Header/ContentMD5.php
<?php /** * @see https://github.com/zendframework/zend-http for the canonical source repository * @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com) * @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License */ namespace Zend\Http\Header; /** * @throws Exception\InvalidArgumentException * @see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.15 */ class ContentMD5 implements HeaderInterface { /** * @var string */ protected $value; public static function fromString($headerLine) { list($name, $value) = GenericHeader::splitHeaderLine($headerLine); // check to ensure proper header type for this factory if (strtolower($name) !== 'content-md5') { throw new Exception\InvalidArgumentException('Invalid header line for Content-MD5 string: "' . $name . '"'); } // @todo implementation details return new static($value); } public function __construct($value = null) { if ($value !== null) { HeaderValue::assertValid($value); $this->value = $value; } } public function getFieldName() { return 'Content-MD5'; } public function getFieldValue() { return (string) $this->value; } public function toString() { return 'Content-MD5: ' . $this->getFieldValue(); } }
php
BSD-3-Clause
ac4ffd09d509b2c5c0285178c4f7de740f05c3d9
2026-01-05T05:18:13.309357Z
false
zendframework/zend-http
https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/src/Header/AcceptCharset.php
src/Header/AcceptCharset.php
<?php /** * @see https://github.com/zendframework/zend-http for the canonical source repository * @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com) * @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License */ namespace Zend\Http\Header; use Zend\Http\Header\Accept\FieldValuePart; /** * Accept Charset Header * * @see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.2 */ class AcceptCharset extends AbstractAccept { protected $regexAddType = '#^([a-zA-Z0-9+-]+|\*)$#'; /** * Get field name * * @return string */ public function getFieldName() { return 'Accept-Charset'; } /** * Cast to string * * @return string */ public function toString() { return 'Accept-Charset: ' . $this->getFieldValue(); } /** * Add a charset, with the given priority * * @param string $type * @param int|float $priority * @return $this */ public function addCharset($type, $priority = 1) { return $this->addType($type, $priority); } /** * Does the header have the requested charset? * * @param string $type * @return bool */ public function hasCharset($type) { return $this->hasType($type); } /** * Parse the keys contained in the header line * * @param string $fieldValuePart * @return \Zend\Http\Header\Accept\FieldValuePart\CharsetFieldValuePart * @see \Zend\Http\Header\AbstractAccept::parseFieldValuePart() */ protected function parseFieldValuePart($fieldValuePart) { $internalValues = parent::parseFieldValuePart($fieldValuePart); return new FieldValuePart\CharsetFieldValuePart($internalValues); } }
php
BSD-3-Clause
ac4ffd09d509b2c5c0285178c4f7de740f05c3d9
2026-01-05T05:18:13.309357Z
false
zendframework/zend-http
https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/src/Header/UserAgent.php
src/Header/UserAgent.php
<?php /** * @see https://github.com/zendframework/zend-http for the canonical source repository * @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com) * @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License */ namespace Zend\Http\Header; /** * @throws Exception\InvalidArgumentException * @see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.43 */ class UserAgent implements HeaderInterface { /** * @var string */ protected $value; public static function fromString($headerLine) { list($name, $value) = GenericHeader::splitHeaderLine($headerLine); // check to ensure proper header type for this factory if (str_replace(['_', ' ', '.'], '-', strtolower($name)) !== 'user-agent') { throw new Exception\InvalidArgumentException('Invalid header line for User-Agent string: "' . $name . '"'); } // @todo implementation details return new static($value); } public function __construct($value = null) { if ($value !== null) { HeaderValue::assertValid($value); $this->value = $value; } } public function getFieldName() { return 'User-Agent'; } public function getFieldValue() { return (string) $this->value; } public function toString() { return 'User-Agent: ' . $this->getFieldValue(); } }
php
BSD-3-Clause
ac4ffd09d509b2c5c0285178c4f7de740f05c3d9
2026-01-05T05:18:13.309357Z
false
zendframework/zend-http
https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/src/Header/Trailer.php
src/Header/Trailer.php
<?php /** * @see https://github.com/zendframework/zend-http for the canonical source repository * @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com) * @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License */ namespace Zend\Http\Header; /** * @throws Exception\InvalidArgumentException * @see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.40 */ class Trailer implements HeaderInterface { /** * @var string */ protected $value; public static function fromString($headerLine) { list($name, $value) = GenericHeader::splitHeaderLine($headerLine); // check to ensure proper header type for this factory if (strtolower($name) !== 'trailer') { throw new Exception\InvalidArgumentException('Invalid header line for Trailer string: "' . $name . '"'); } // @todo implementation details return new static($value); } public function __construct($value = null) { if ($value !== null) { HeaderValue::assertValid($value); $this->value = $value; } } public function getFieldName() { return 'Trailer'; } public function getFieldValue() { return (string) $this->value; } public function toString() { return 'Trailer: ' . $this->getFieldValue(); } }
php
BSD-3-Clause
ac4ffd09d509b2c5c0285178c4f7de740f05c3d9
2026-01-05T05:18:13.309357Z
false
zendframework/zend-http
https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/src/Header/Accept.php
src/Header/Accept.php
<?php /** * @see https://github.com/zendframework/zend-http for the canonical source repository * @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com) * @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License */ namespace Zend\Http\Header; use Zend\Http\Header\Accept\FieldValuePart; /** * Accept Header * * @see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.1 */ class Accept extends AbstractAccept { /** * @var string */ protected $regexAddType = '#^([a-zA-Z+-]+|\*)/(\*|[a-zA-Z0-9+-]+)$#'; /** * Get field name * * @return string */ public function getFieldName() { return 'Accept'; } /** * Cast to string * * @return string */ public function toString() { return 'Accept: ' . $this->getFieldValue(); } /** * Add a media type, with the given priority * * @param string $type * @param int|float $priority * @param array $params * @return $this */ public function addMediaType($type, $priority = 1, array $params = []) { return $this->addType($type, $priority, $params); } /** * Does the header have the requested media type? * * @param string $type * @return bool */ public function hasMediaType($type) { return $this->hasType($type); } /** * Parse the keys contained in the header line * * @param string $fieldValuePart * @return FieldValuePart\AcceptFieldValuePart * @see \Zend\Http\Header\AbstractAccept::parseFieldValuePart() */ protected function parseFieldValuePart($fieldValuePart) { $raw = $fieldValuePart; if ($pos = strpos($fieldValuePart, '/')) { $type = trim(substr($fieldValuePart, 0, $pos)); } else { $type = trim($fieldValuePart); } $params = $this->getParametersFromFieldValuePart($fieldValuePart); if ($pos = strpos($fieldValuePart, ';')) { $fieldValuePart = trim(substr($fieldValuePart, 0, $pos)); } if (strpos($fieldValuePart, '/')) { $subtypeWhole = $format = $subtype = trim(substr($fieldValuePart, strpos($fieldValuePart, '/') + 1)); } else { $subtypeWhole = ''; $format = '*'; $subtype = '*'; } $pos = strpos($subtype, '+'); if (false !== $pos) { $format = trim(substr($subtype, $pos + 1)); $subtype = trim(substr($subtype, 0, $pos)); } $aggregated = [ 'typeString' => trim($fieldValuePart), 'type' => $type, 'subtype' => $subtype, 'subtypeRaw' => $subtypeWhole, 'format' => $format, 'priority' => isset($params['q']) ? $params['q'] : 1, 'params' => $params, 'raw' => trim($raw), ]; return new FieldValuePart\AcceptFieldValuePart((object) $aggregated); } }
php
BSD-3-Clause
ac4ffd09d509b2c5c0285178c4f7de740f05c3d9
2026-01-05T05:18:13.309357Z
false
zendframework/zend-http
https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/src/Header/ContentType.php
src/Header/ContentType.php
<?php /** * @see https://github.com/zendframework/zend-http for the canonical source repository * @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com) * @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License */ namespace Zend\Http\Header; use stdClass; /** * @throws Exception\InvalidArgumentException * @see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.17 */ class ContentType implements HeaderInterface { /** * @var string */ protected $mediaType; /** * @var array */ protected $parameters = []; /** * @var string */ protected $value; /** * Factory method: create an object from a string representation * * @param string $headerLine * @return static */ public static function fromString($headerLine) { list($name, $value) = GenericHeader::splitHeaderLine($headerLine); // check to ensure proper header type for this factory if (strtolower($name) !== 'content-type') { throw new Exception\InvalidArgumentException(sprintf( 'Invalid header line for Content-Type string: "%s"', $name )); } $parts = explode(';', $value); $mediaType = array_shift($parts); $header = new static($value, trim($mediaType)); if (count($parts) > 0) { $parameters = []; foreach ($parts as $parameter) { $parameter = trim($parameter); if (! preg_match('/^(?P<key>[^\s\=]+)\="?(?P<value>[^\s\"]*)"?$/', $parameter, $matches)) { continue; } $parameters[$matches['key']] = $matches['value']; } $header->setParameters($parameters); } return $header; } public function __construct($value = null, $mediaType = null) { if ($value !== null) { HeaderValue::assertValid($value); $this->value = $value; } $this->mediaType = $mediaType; } /** * Determine if the mediatype value in this header matches the provided criteria * * @param array|string $matchAgainst * @return string|bool Matched value or false */ public function match($matchAgainst) { if (is_string($matchAgainst)) { $matchAgainst = $this->splitMediaTypesFromString($matchAgainst); } $mediaType = $this->getMediaType(); $left = $this->getMediaTypeObjectFromString($mediaType); foreach ($matchAgainst as $matchType) { $matchType = strtolower($matchType); if ($mediaType == $matchType) { return $matchType; } $right = $this->getMediaTypeObjectFromString($matchType); // Is the right side a wildcard type? if ($right->type == '*') { if ($this->validateSubtype($right, $left)) { return $matchType; } } // Do the types match? if ($right->type == $left->type) { if ($this->validateSubtype($right, $left)) { return $matchType; } } } return false; } /** * Create a string representation of the header * * @return string */ public function toString() { return 'Content-Type: ' . $this->getFieldValue(); } /** * Get the field name * * @return string */ public function getFieldName() { return 'Content-Type'; } /** * Get the field value * * @return string */ public function getFieldValue() { if (null !== $this->value) { return (string) $this->value; } return $this->assembleValue(); } /** * Set the media type * * @param string $mediaType * @return $this */ public function setMediaType($mediaType) { HeaderValue::assertValid($mediaType); $this->mediaType = strtolower($mediaType); $this->value = null; return $this; } /** * Get the media type * * @return string */ public function getMediaType() { return (string) $this->mediaType; } /** * Set additional content-type parameters * * @param array $parameters * @return $this */ public function setParameters(array $parameters) { foreach ($parameters as $key => $value) { HeaderValue::assertValid($key); HeaderValue::assertValid($value); } $this->parameters = array_merge($this->parameters, $parameters); $this->value = null; return $this; } /** * Get any additional content-type parameters currently set * * @return array */ public function getParameters() { return $this->parameters; } /** * Set the content-type character set encoding * * @param string $charset * @return $this */ public function setCharset($charset) { HeaderValue::assertValid($charset); $this->parameters['charset'] = $charset; $this->value = null; return $this; } /** * Get the content-type character set encoding, if any * * @return null|string */ public function getCharset() { if (isset($this->parameters['charset'])) { return $this->parameters['charset']; } return null; } /** * Assemble the value based on the media type and any available parameters * * @return string */ protected function assembleValue() { $mediaType = $this->getMediaType(); if (empty($this->parameters)) { return $mediaType; } $parameters = []; foreach ($this->parameters as $key => $value) { $parameters[] = sprintf('%s=%s', $key, $value); } return sprintf('%s; %s', $mediaType, implode('; ', $parameters)); } /** * Split comma-separated media types into an array * * @param string $criteria * @return array */ protected function splitMediaTypesFromString($criteria) { $mediaTypes = explode(',', $criteria); array_walk( $mediaTypes, function (&$value) { $value = trim($value); } ); return $mediaTypes; } /** * Split a mediatype string into an object with the following parts: * * - type * - subtype * - format * * @param string $string * @return stdClass */ protected function getMediaTypeObjectFromString($string) { if (! is_string($string)) { throw new Exception\InvalidArgumentException(sprintf( 'Non-string mediatype "%s" provided', (is_object($string) ? get_class($string) : gettype($string)) )); } $parts = explode('/', $string, 2); if (1 == count($parts)) { throw new Exception\DomainException(sprintf( 'Invalid mediatype "%s" provided', $string )); } $type = array_shift($parts); $subtype = array_shift($parts); $format = $subtype; if (false !== strpos($subtype, '+')) { $parts = explode('+', $subtype, 2); $subtype = array_shift($parts); $format = array_shift($parts); } $mediaType = (object) [ 'type' => $type, 'subtype' => $subtype, 'format' => $format, ]; return $mediaType; } /** * Validate a subtype * * @param stdClass $right * @param stdClass $left * @return bool */ protected function validateSubtype($right, $left) { // Is the right side a wildcard subtype? if ($right->subtype == '*') { return $this->validateFormat($right, $left); } // Do the right side and left side subtypes match? if ($right->subtype == $left->subtype) { return $this->validateFormat($right, $left); } // Is the right side a partial wildcard? if ('*' == substr($right->subtype, -1)) { // validate partial-wildcard subtype if (! $this->validatePartialWildcard($right->subtype, $left->subtype)) { return false; } // Finally, verify format is valid return $this->validateFormat($right, $left); } // Does the right side subtype match the left side format? if ($right->subtype == $left->format) { return true; } // At this point, there is no valid match return false; } /** * Validate the format * * Validate that the right side format matches what the left side defines. * * @param string $right * @param string $left * @return bool */ protected function validateFormat($right, $left) { if ($right->format && $left->format) { if ($right->format == '*') { return true; } if ($right->format == $left->format) { return true; } return false; } return true; } /** * Validate a partial wildcard (i.e., string ending in '*') * * @param string $right * @param string $left * @return bool */ protected function validatePartialWildcard($right, $left) { $requiredSegment = substr($right, 0, strlen($right) - 1); if ($requiredSegment == $left) { return true; } if (strlen($requiredSegment) >= strlen($left)) { return false; } if (0 === strpos($left, $requiredSegment)) { return true; } return false; } }
php
BSD-3-Clause
ac4ffd09d509b2c5c0285178c4f7de740f05c3d9
2026-01-05T05:18:13.309357Z
false
zendframework/zend-http
https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/src/Header/AcceptLanguage.php
src/Header/AcceptLanguage.php
<?php /** * @see https://github.com/zendframework/zend-http for the canonical source repository * @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com) * @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License */ namespace Zend\Http\Header; use Zend\Http\Header\Accept\FieldValuePart; /** * Accept Language Header * * @see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.4 */ class AcceptLanguage extends AbstractAccept { protected $regexAddType = '#^([a-zA-Z0-9+-]+|\*)$#'; /** * Get field name * * @return string */ public function getFieldName() { return 'Accept-Language'; } /** * Cast to string * * @return string */ public function toString() { return 'Accept-Language: ' . $this->getFieldValue(); } /** * Add a language, with the given priority * * @param string $type * @param int|float $priority * @return $this */ public function addLanguage($type, $priority = 1) { return $this->addType($type, $priority); } /** * Does the header have the requested language? * * @param string $type * @return bool */ public function hasLanguage($type) { return $this->hasType($type); } /** * Parse the keys contained in the header line * * @param string $fieldValuePart * @return \Zend\Http\Header\Accept\FieldValuePart\LanguageFieldValuePart * @see \Zend\Http\Header\AbstractAccept::parseFieldValuePart() */ protected function parseFieldValuePart($fieldValuePart) { $raw = $fieldValuePart; if ($pos = strpos($fieldValuePart, '-')) { $type = trim(substr($fieldValuePart, 0, $pos)); } else { $type = trim(substr($fieldValuePart, 0)); } $params = $this->getParametersFromFieldValuePart($fieldValuePart); if ($pos = strpos($fieldValuePart, ';')) { $fieldValuePart = $type = trim(substr($fieldValuePart, 0, $pos)); } if (strpos($fieldValuePart, '-')) { $subtypeWhole = $format = $subtype = trim(substr($fieldValuePart, strpos($fieldValuePart, '-') + 1)); } else { $subtypeWhole = ''; $format = '*'; $subtype = '*'; } $aggregated = [ 'typeString' => trim($fieldValuePart), 'type' => $type, 'subtype' => $subtype, 'subtypeRaw' => $subtypeWhole, 'format' => $format, 'priority' => isset($params['q']) ? $params['q'] : 1, 'params' => $params, 'raw' => trim($raw), ]; return new FieldValuePart\LanguageFieldValuePart((object) $aggregated); } }
php
BSD-3-Clause
ac4ffd09d509b2c5c0285178c4f7de740f05c3d9
2026-01-05T05:18:13.309357Z
false
zendframework/zend-http
https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/src/Header/CacheControl.php
src/Header/CacheControl.php
<?php /** * @see https://github.com/zendframework/zend-http for the canonical source repository * @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com) * @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License */ namespace Zend\Http\Header; /** * @throws Exception\InvalidArgumentException * @see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.9 */ class CacheControl implements HeaderInterface { /** * @var string */ protected $value; /** * Array of Cache-Control directives * * @var array */ protected $directives = []; /** * Creates a CacheControl object from a headerLine * * @param string $headerLine * @throws Exception\InvalidArgumentException * @return static */ public static function fromString($headerLine) { list($name, $value) = GenericHeader::splitHeaderLine($headerLine); // check to ensure proper header type for this factory if (strtolower($name) !== 'cache-control') { throw new Exception\InvalidArgumentException(sprintf( 'Invalid header line for Cache-Control string: "%s"', $name )); } HeaderValue::assertValid($value); $directives = static::parseValue($value); // @todo implementation details $header = new static(); foreach ($directives as $key => $value) { $header->addDirective($key, $value); } return $header; } /** * Required from HeaderDescription interface * * @return string */ public function getFieldName() { return 'Cache-Control'; } /** * Checks if the internal directives array is empty * * @return bool */ public function isEmpty() { return empty($this->directives); } /** * Add a directive * For directives like 'max-age=60', $value = '60' * For directives like 'private', use the default $value = true * * @param string $key * @param string|bool $value * @return $this */ public function addDirective($key, $value = true) { HeaderValue::assertValid($key); if (! is_bool($value)) { HeaderValue::assertValid($value); } $this->directives[$key] = $value; return $this; } /** * Check the internal directives array for a directive * * @param string $key * @return bool */ public function hasDirective($key) { return array_key_exists($key, $this->directives); } /** * Fetch the value of a directive from the internal directive array * * @param string $key * @return string|null */ public function getDirective($key) { return array_key_exists($key, $this->directives) ? $this->directives[$key] : null; } /** * Remove a directive * * @param string $key * @return $this */ public function removeDirective($key) { unset($this->directives[$key]); return $this; } /** * Assembles the directives into a comma-delimited string * * @return string */ public function getFieldValue() { $parts = []; ksort($this->directives); foreach ($this->directives as $key => $value) { if (true === $value) { $parts[] = $key; } else { if (preg_match('#[^a-zA-Z0-9._-]#', $value)) { $value = '"' . $value . '"'; } $parts[] = $key . '=' . $value; } } return implode(', ', $parts); } /** * Returns a string representation of the HTTP Cache-Control header * * @return string */ public function toString() { return 'Cache-Control: ' . $this->getFieldValue(); } /** * Internal function for parsing the value part of a * HTTP Cache-Control header * * @param string $value * @throws Exception\InvalidArgumentException * @return array */ protected static function parseValue($value) { $value = trim($value); $directives = []; // handle empty string early so we don't need a separate start state if ($value == '') { return $directives; } $lastMatch = null; state_directive: switch (static::match(['[a-zA-Z][a-zA-Z_-]*'], $value, $lastMatch)) { case 0: $directive = $lastMatch; goto state_value; // intentional fall-through default: throw new Exception\InvalidArgumentException('expected DIRECTIVE'); } state_value: switch (static::match(['="[^"]*"', '=[^",\s;]*'], $value, $lastMatch)) { case 0: $directives[$directive] = substr($lastMatch, 2, -1); goto state_separator; // intentional fall-through case 1: $directives[$directive] = rtrim(substr($lastMatch, 1)); goto state_separator; // intentional fall-through default: $directives[$directive] = true; goto state_separator; } state_separator: switch (static::match(['\s*,\s*', '$'], $value, $lastMatch)) { case 0: goto state_directive; // intentional fall-through case 1: return $directives; default: throw new Exception\InvalidArgumentException('expected SEPARATOR or END'); } } /** * Internal function used by parseValue to match tokens * * @param array $tokens * @param string $string * @param string $lastMatch * @return int */ protected static function match($tokens, &$string, &$lastMatch) { // Ensure we have a string $value = (string) $string; foreach ($tokens as $i => $token) { if (preg_match('/^' . $token . '/', $value, $matches)) { $lastMatch = $matches[0]; $string = substr($value, strlen($matches[0])); return $i; } } return -1; } }
php
BSD-3-Clause
ac4ffd09d509b2c5c0285178c4f7de740f05c3d9
2026-01-05T05:18:13.309357Z
false
zendframework/zend-http
https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/src/Header/ContentEncoding.php
src/Header/ContentEncoding.php
<?php /** * @see https://github.com/zendframework/zend-http for the canonical source repository * @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com) * @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License */ namespace Zend\Http\Header; /** * @throws Exception\InvalidArgumentException * @see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.11 */ class ContentEncoding implements HeaderInterface { /** * @var string */ protected $value; public static function fromString($headerLine) { list($name, $value) = GenericHeader::splitHeaderLine($headerLine); // check to ensure proper header type for this factory if (strtolower($name) !== 'content-encoding') { throw new Exception\InvalidArgumentException( 'Invalid header line for Content-Encoding string: "' . $name . '"' ); } // @todo implementation details return new static($value); } public function __construct($value = null) { if ($value !== null) { HeaderValue::assertValid($value); $this->value = $value; } } public function getFieldName() { return 'Content-Encoding'; } public function getFieldValue() { return (string) $this->value; } public function toString() { return 'Content-Encoding: ' . $this->getFieldValue(); } }
php
BSD-3-Clause
ac4ffd09d509b2c5c0285178c4f7de740f05c3d9
2026-01-05T05:18:13.309357Z
false
zendframework/zend-http
https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/src/Header/Age.php
src/Header/Age.php
<?php /** * @see https://github.com/zendframework/zend-http for the canonical source repository * @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com) * @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License */ namespace Zend\Http\Header; /** * Age HTTP Header * * @link http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.6 */ class Age implements HeaderInterface { /** * Estimate of the amount of time in seconds since the response * * @var int */ protected $deltaSeconds; /** * Create Age header from string * * @param string $headerLine * @return static * @throws Exception\InvalidArgumentException */ public static function fromString($headerLine) { list($name, $value) = GenericHeader::splitHeaderLine($headerLine); // check to ensure proper header type for this factory if (strtolower($name) !== 'age') { throw new Exception\InvalidArgumentException('Invalid header line for Age string: "' . $name . '"'); } return new static($value); } public function __construct($deltaSeconds = null) { if ($deltaSeconds !== null) { $this->setDeltaSeconds($deltaSeconds); } } /** * Get header name * * @return string */ public function getFieldName() { return 'Age'; } /** * Get header value (number of seconds) * * @return string */ public function getFieldValue() { return (string) $this->getDeltaSeconds(); } /** * Set number of seconds * * @param int $delta * @return $this */ public function setDeltaSeconds($delta) { if (! is_int($delta) && ! is_numeric($delta)) { throw new Exception\InvalidArgumentException('Invalid delta provided'); } $this->deltaSeconds = (int) $delta; return $this; } /** * Get number of seconds * * @return int */ public function getDeltaSeconds() { return $this->deltaSeconds; } /** * Return header line * In case of overflow RFC states to set value of 2147483648 (2^31) * * @return string */ public function toString() { return 'Age: ' . (($this->deltaSeconds >= PHP_INT_MAX) ? '2147483648' : $this->deltaSeconds); } }
php
BSD-3-Clause
ac4ffd09d509b2c5c0285178c4f7de740f05c3d9
2026-01-05T05:18:13.309357Z
false
zendframework/zend-http
https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/src/Header/AcceptRanges.php
src/Header/AcceptRanges.php
<?php /** * @see https://github.com/zendframework/zend-http for the canonical source repository * @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com) * @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License */ namespace Zend\Http\Header; /** * Accept Ranges Header * * @see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.5 */ class AcceptRanges implements HeaderInterface { protected $rangeUnit; public static function fromString($headerLine) { list($name, $value) = GenericHeader::splitHeaderLine($headerLine); // check to ensure proper header type for this factory if (strtolower($name) !== 'accept-ranges') { throw new Exception\InvalidArgumentException( 'Invalid header line for Accept-Ranges string' ); } return new static($value); } public function __construct($rangeUnit = null) { if ($rangeUnit !== null) { $this->setRangeUnit($rangeUnit); } } public function getFieldName() { return 'Accept-Ranges'; } public function getFieldValue() { return $this->getRangeUnit(); } public function setRangeUnit($rangeUnit) { HeaderValue::assertValid($rangeUnit); $this->rangeUnit = $rangeUnit; return $this; } public function getRangeUnit() { return (string) $this->rangeUnit; } public function toString() { return 'Accept-Ranges: ' . $this->getFieldValue(); } }
php
BSD-3-Clause
ac4ffd09d509b2c5c0285178c4f7de740f05c3d9
2026-01-05T05:18:13.309357Z
false
zendframework/zend-http
https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/src/Header/Refresh.php
src/Header/Refresh.php
<?php /** * @see https://github.com/zendframework/zend-http for the canonical source repository * @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com) * @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License */ namespace Zend\Http\Header; /** * @throws Exception\InvalidArgumentException * @todo FIND SPEC FOR THIS */ class Refresh implements HeaderInterface { /** * @var string */ protected $value; public static function fromString($headerLine) { list($name, $value) = GenericHeader::splitHeaderLine($headerLine); // check to ensure proper header type for this factory if (strtolower($name) !== 'refresh') { throw new Exception\InvalidArgumentException('Invalid header line for Refresh string: "' . $name . '"'); } // @todo implementation details return new static($value); } public function __construct($value = null) { if ($value !== null) { HeaderValue::assertValid($value); $this->value = $value; } } public function getFieldName() { return 'Refresh'; } public function getFieldValue() { return (string) $this->value; } public function toString() { return 'Refresh: ' . $this->getFieldValue(); } }
php
BSD-3-Clause
ac4ffd09d509b2c5c0285178c4f7de740f05c3d9
2026-01-05T05:18:13.309357Z
false
zendframework/zend-http
https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/src/Header/TransferEncoding.php
src/Header/TransferEncoding.php
<?php /** * @see https://github.com/zendframework/zend-http for the canonical source repository * @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com) * @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License */ namespace Zend\Http\Header; /** * @throws Exception\InvalidArgumentException * @see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.41 */ class TransferEncoding implements HeaderInterface { /** * @var string */ protected $value; public static function fromString($headerLine) { list($name, $value) = GenericHeader::splitHeaderLine($headerLine); // check to ensure proper header type for this factory if (strtolower($name) !== 'transfer-encoding') { throw new Exception\InvalidArgumentException( 'Invalid header line for Transfer-Encoding string: "' . $name . '"' ); } // @todo implementation details return new static($value); } public function __construct($value = null) { if ($value !== null) { HeaderValue::assertValid($value); $this->value = $value; } } public function getFieldName() { return 'Transfer-Encoding'; } public function getFieldValue() { return (string) $this->value; } public function toString() { return 'Transfer-Encoding: ' . $this->getFieldValue(); } }
php
BSD-3-Clause
ac4ffd09d509b2c5c0285178c4f7de740f05c3d9
2026-01-05T05:18:13.309357Z
false
zendframework/zend-http
https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/src/Header/ContentLength.php
src/Header/ContentLength.php
<?php /** * @see https://github.com/zendframework/zend-http for the canonical source repository * @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com) * @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License */ namespace Zend\Http\Header; /** * @throws Exception\InvalidArgumentException * @see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.13 */ class ContentLength implements HeaderInterface { /** * @var string */ protected $value; public static function fromString($headerLine) { list($name, $value) = GenericHeader::splitHeaderLine($headerLine); // check to ensure proper header type for this factory if (strtolower($name) !== 'content-length') { throw new Exception\InvalidArgumentException(sprintf( 'Invalid header line for Content-Length string: "%s"', $name )); } // @todo implementation details return new static($value); } public function __construct($value = null) { if (null !== $value) { HeaderValue::assertValid($value); $this->value = $value; } } public function getFieldName() { return 'Content-Length'; } public function getFieldValue() { return (string) $this->value; } public function toString() { return 'Content-Length: ' . $this->getFieldValue(); } }
php
BSD-3-Clause
ac4ffd09d509b2c5c0285178c4f7de740f05c3d9
2026-01-05T05:18:13.309357Z
false