1: <?php
2:
3: namespace Zippy;
4:
5: /**
6: * Класс формирующий ответ клиенту (браузеру). Создается приложеем.
7: */
8: class HttpResponse
9: {
10: private $content;
11: // private $ajaxanswer = "";
12: public $SSRrender = "";
13: public $JSrender = "";
14: public $JSrenderDocReady = "";
15: private $pageindex;
16: public $binaryanswer;
17: private $gzip = false;
18: private $redirect = "";
19: public $page404 = null;
20:
21: public function __construct() {
22: //$this->setRequestIndex(WebApplication::$app->getRequest()->getRequestIndex())
23:
24: }
25:
26: /**
27: * Формирует выходной поток данных
28: * @return string
29: */
30: public function output() {
31: if (strlen($this->redirect) > 0) {
32: header("Location: " . $this->redirect);
33: // echo "<script>window.location='{$this->redirect}'</script>";
34: die;
35: }
36: if (WebApplication::$app->getRequest()->isBinaryRequest() == true) {
37: // вывод осуществляет адресуемый компонент
38: return;
39: }
40:
41: Header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
42: Header("Cache-Control: no-store,no-cache, must-revalidate");
43: Header("Pragma: no-cache");
44: Header("Last-Modified: Mon, 26 Jul 2100 05:00:00 GMT");
45:
46: if (WebApplication::$app->getRequest()->isAjaxRequest() == true) {
47: $this->content = trim($this->content) ;
48: if(strpos($this->content,"{")===0) {
49: Header("Content-Type: application/json;charset=UTF-8");
50: } else {
51: Header("Content-Type: text/javascript;charset=UTF-8");
52: }
53: echo $this->content;
54: return;
55: }
56: Header("Content-Type: text/html;charset=UTF-8");
57:
58: if (strpos($this->content, "</head>") > 0) {
59: $this->content = str_replace("</head>", $this->getJS() . "</head>", $this->content);
60: } else {
61: $this->content = $this->content . $this->getJS();
62: }
63:
64: if (WebApplication::$app->getRequest()->isAjaxRequest() == false && $this->gzip === true && strpos($_SERVER["HTTP_ACCEPT_ENCODING"], "gzip") !== false) {
65: Header("Content-Encoding: gzip");
66: echo gzencode($this->content . $this->getJS());
67: return;
68: }
69: echo $this->content;
70: }
71:
72: /**
73: * редирект на главную страницу
74: *
75: */
76: public function toIndexPage() {
77: $this->redirect = "/";
78: // header("Location: /index.php");
79: // die;
80: }
81:
82: /**
83: * Редирект непосредственно по адресу
84: *
85: */
86: public function toPage($url) {
87: $this->redirect = $url;
88: }
89:
90: /**
91: * редирект на текущую страницу без параметров
92: * (применяется для "сброса" адресной строки
93: *
94: */
95: public function toBaseUrl() {
96: if (strlen($this->redirect) == 0) { //если не было редиректа
97: $this->redirect = $this->getBaseUrl();
98: }
99: }
100:
101: /**
102: * Добавляет JavaScript код для AJAX ответа
103: *
104: * @param mixed $js
105: */
106: public function addAjaxResponse($js) {
107:
108: $this->content .= ($js . " \n");
109: }
110:
111: /**
112: * Вставляет JavaScript в конец выходного потока страницы
113: * @param string Код скрипта
114: * @param boolean Если true - вставка после загрузки (onload) документа в браузер
115: */
116: public function addJavaScript($js, $docready = false) {
117:
118: if ($docready === true) {
119: $this->JSrenderDocReady .= ($js . " \n");
120: } else {
121: $this->JSrender .= ($js . " \n");
122: }
123: }
124:
125: /**
126: * Возвращает результирующий JavaScript код при формировании выходного HTML потока
127: * @return string JavaScript код
128: */
129: private function getJS() {
130:
131: if (strlen($this->JSrenderDocReady . $this->JSrender) == 0) {
132: return "";
133: }
134:
135: $js = "
136: <script type=\"text/javascript\">
137: //сгенерировано фреймворком
138: ";
139: if (strlen($this->JSrenderDocReady) > 0) {
140: $js .= " $(document).ready(function()
141: {
142: {$this->JSrenderDocReady}
143: } )
144: ";
145: }
146: $js .= $this->JSrender . "
147:
148: //сгенерировано фреймворком
149: </script>";
150:
151: return $js;
152: }
153:
154: /**
155: * Возвращает для дочерних елементов базовую часть URL с номером и версией страницы
156: * @return string
157: */
158: final public function getBaseUrl() {
159: $pagename = get_class(WebApplication::$app->getCurrentPage());
160: $pagename = str_replace("\\", "/", $pagename);
161: // return $this->getHostUrl() . "/index.php?q=p:" . $pagename ;
162: return "/index.php?q=p:" . $pagename ;
163:
164: }
165:
166: /**
167: * Создает новый экземпляр страницы по имени класса страницы
168: * делает ее текущей и перенаправляет на нее HTTP запрос с клиента
169: * (клиентский редирект, сбрасывающий адресную строку браузера).
170: * @param string Имя класса страницы
171: * @param array массив параметров страницы
172: *
173: */
174: final public function Redirect($name, $arg1 = null, $arg2 = null, $arg3 = null, $arg4 = null, $arg5 = null) {
175: if ($name instanceof \Zippy\Html\WebPage) {
176: $name = get_class($name);
177: }
178:
179: WebApplication::$app->LoadPage($name, $arg1, $arg2, $arg3, $arg4, $arg5);
180: // $url = "/index.php?q=" . $this->getPageManager()->session->putPage($this->currentpage) . "::1";
181: // $this->saveSession(serialize($this->session));
182: $this->toBaseUrl();
183: $this->output();
184: }
185:
186: final public function setContent($content) {
187: $this->content = $content;
188: }
189:
190: /**
191: *
192: * @return string
193: */
194: final public function getHostUrl() {
195: $http = 'http';
196: if (isset($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) !== 'off') {
197: $http = 'https';
198: } elseif (!empty($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https' || !empty($_SERVER['HTTP_X_FORWARDED_SSL']) && $_SERVER['HTTP_X_FORWARDED_SSL'] == 'on') {
199: $http = 'https';
200: } elseif(443 == intval($_SERVER['SERVER_PORT'])) {
201: $http = 'https';
202: }
203:
204: $url = $http . "://" . $_SERVER["HTTP_HOST"];
205: return $url;
206: }
207:
208: final public function setPageIndex($index) {
209: $this->pageindex = $index;
210: }
211:
212: /**
213: * сжимать данные для браузера
214: *
215: * @param mixed $gzip true false
216: */
217: final public function setGzip($gzip) {
218: $this->gzip = $gzip;
219: }
220:
221: final public function isRedirect() {
222: return strlen($this->redirect) > 0;
223: }
224:
225: /**
226: * Перенаправляет на страницу 404
227: *
228: */
229: public function to404Page() {
230:
231: header("HTTP/1.0 404 Not Found");
232:
233: die;
234: }
235:
236: /**
237: * редирект на предыдущую страницу
238: */
239: /*
240: public final function toBack()
241: {
242: $pagename = WebApplication::$app->getPrevPage();
243:
244: // $pagename = str_replace("\\", "/", $pagename);
245: $pagename = '\\' . rtrim($pagename, '\\');
246: //$this->redirect = $this->getHostUrl() . "/index.php?q=" . $pagename . ":" . $this->pageindex--;
247: if($pagename== "\\") {
248: $this->toIndexPage();
249: return;
250: }
251: $this->Redirect($pagename, array());
252: }
253: */
254: }
255: