2
0

Abstract.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755
  1. <?php
  2. /**
  3. * Zend Framework
  4. *
  5. * LICENSE
  6. *
  7. * This source file is subject to the new BSD license that is bundled
  8. * with this package in the file LICENSE.txt.
  9. * It is also available through the world-wide-web at this URL:
  10. * http://framework.zend.com/license/new-bsd
  11. * If you did not receive a copy of the license and are unable to
  12. * obtain it through the world-wide-web, please send an email
  13. * to license@zend.com so we can send you a copy immediately.
  14. *
  15. * @category Zend
  16. * @package Zend_Controller
  17. * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com)
  18. * @license http://framework.zend.com/license/new-bsd New BSD License
  19. * @version $Id$
  20. */
  21. /**
  22. * Zend_Controller_Response_Abstract
  23. *
  24. * Base class for Zend_Controller responses
  25. *
  26. * @package Zend_Controller
  27. * @subpackage Response
  28. * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com)
  29. * @license http://framework.zend.com/license/new-bsd New BSD License
  30. */
  31. abstract class Zend_Controller_Response_Abstract
  32. {
  33. /**
  34. * Body content
  35. * @var array
  36. */
  37. protected $_body = array();
  38. /**
  39. * Exception stack
  40. * @var Exception
  41. */
  42. protected $_exceptions = array();
  43. /**
  44. * Array of headers. Each header is an array with keys 'name' and 'value'
  45. * @var array
  46. */
  47. protected $_headers = array();
  48. /**
  49. * Array of raw headers. Each header is a single string, the entire header to emit
  50. * @var array
  51. */
  52. protected $_headersRaw = array();
  53. /**
  54. * HTTP response code to use in headers
  55. * @var int
  56. */
  57. protected $_httpResponseCode = 200;
  58. /**
  59. * Flag; is this response a redirect?
  60. * @var boolean
  61. */
  62. protected $_isRedirect = false;
  63. /**
  64. * Whether or not to render exceptions; off by default
  65. * @var boolean
  66. */
  67. protected $_renderExceptions = false;
  68. /**
  69. * Flag; if true, when header operations are called after headers have been
  70. * sent, an exception will be raised; otherwise, processing will continue
  71. * as normal. Defaults to true.
  72. *
  73. * @see canSendHeaders()
  74. * @var boolean
  75. */
  76. public $headersSentThrowsException = true;
  77. /**
  78. * Normalize a header name
  79. *
  80. * Normalizes a header name to X-Capitalized-Names
  81. *
  82. * @param string $name
  83. * @return string
  84. */
  85. protected function _normalizeHeader($name)
  86. {
  87. $filtered = str_replace(array('-', '_'), ' ', (string) $name);
  88. $filtered = ucwords(strtolower($filtered));
  89. $filtered = str_replace(' ', '-', $filtered);
  90. return $filtered;
  91. }
  92. /**
  93. * Set a header
  94. *
  95. * If $replace is true, replaces any headers already defined with that
  96. * $name.
  97. *
  98. * @param string $name
  99. * @param string $value
  100. * @param boolean $replace
  101. * @return Zend_Controller_Response_Abstract
  102. */
  103. public function setHeader($name, $value, $replace = false)
  104. {
  105. $this->canSendHeaders(true);
  106. $name = $this->_normalizeHeader($name);
  107. $value = (string) $value;
  108. if ($replace) {
  109. foreach ($this->_headers as $key => $header) {
  110. if ($name == $header['name']) {
  111. unset($this->_headers[$key]);
  112. }
  113. }
  114. }
  115. $this->_headers[] = array(
  116. 'name' => $name,
  117. 'value' => $value,
  118. 'replace' => $replace
  119. );
  120. return $this;
  121. }
  122. /**
  123. * Set redirect URL
  124. *
  125. * Sets Location header and response code. Forces replacement of any prior
  126. * redirects.
  127. *
  128. * @param string $url
  129. * @param int $code
  130. * @return Zend_Controller_Response_Abstract
  131. */
  132. public function setRedirect($url, $code = 302)
  133. {
  134. $this->canSendHeaders(true);
  135. $this->setHeader('Location', $url, true)
  136. ->setHttpResponseCode($code);
  137. return $this;
  138. }
  139. /**
  140. * Is this a redirect?
  141. *
  142. * @return boolean
  143. */
  144. public function isRedirect()
  145. {
  146. return $this->_isRedirect;
  147. }
  148. /**
  149. * Return array of headers; see {@link $_headers} for format
  150. *
  151. * @return array
  152. */
  153. public function getHeaders()
  154. {
  155. return $this->_headers;
  156. }
  157. /**
  158. * Clear headers
  159. *
  160. * @return Zend_Controller_Response_Abstract
  161. */
  162. public function clearHeaders()
  163. {
  164. $this->_headers = array();
  165. return $this;
  166. }
  167. /**
  168. * Set raw HTTP header
  169. *
  170. * Allows setting non key => value headers, such as status codes
  171. *
  172. * @param string $value
  173. * @return Zend_Controller_Response_Abstract
  174. */
  175. public function setRawHeader($value)
  176. {
  177. $this->canSendHeaders(true);
  178. if ('Location' == substr($value, 0, 8)) {
  179. $this->_isRedirect = true;
  180. }
  181. $this->_headersRaw[] = (string) $value;
  182. return $this;
  183. }
  184. /**
  185. * Retrieve all {@link setRawHeader() raw HTTP headers}
  186. *
  187. * @return array
  188. */
  189. public function getRawHeaders()
  190. {
  191. return $this->_headersRaw;
  192. }
  193. /**
  194. * Clear all {@link setRawHeader() raw HTTP headers}
  195. *
  196. * @return Zend_Controller_Response_Abstract
  197. */
  198. public function clearRawHeaders()
  199. {
  200. $this->_headersRaw = array();
  201. return $this;
  202. }
  203. /**
  204. * Clear all headers, normal and raw
  205. *
  206. * @return Zend_Controller_Response_Abstract
  207. */
  208. public function clearAllHeaders()
  209. {
  210. return $this->clearHeaders()
  211. ->clearRawHeaders();
  212. }
  213. /**
  214. * Set HTTP response code to use with headers
  215. *
  216. * @param int $code
  217. * @return Zend_Controller_Response_Abstract
  218. */
  219. public function setHttpResponseCode($code)
  220. {
  221. if (!is_int($code) || (100 > $code) || (599 < $code)) {
  222. require_once 'Zend/Controller/Response/Exception.php';
  223. throw new Zend_Controller_Response_Exception('Invalid HTTP response code');
  224. }
  225. if ((300 <= $code) && (307 >= $code)) {
  226. $this->_isRedirect = true;
  227. } else {
  228. $this->_isRedirect = false;
  229. }
  230. $this->_httpResponseCode = $code;
  231. return $this;
  232. }
  233. /**
  234. * Retrieve HTTP response code
  235. *
  236. * @return int
  237. */
  238. public function getHttpResponseCode()
  239. {
  240. return $this->_httpResponseCode;
  241. }
  242. /**
  243. * Can we send headers?
  244. *
  245. * @param boolean $throw Whether or not to throw an exception if headers have been sent; defaults to false
  246. * @return boolean
  247. * @throws Zend_Controller_Response_Exception
  248. */
  249. public function canSendHeaders($throw = false)
  250. {
  251. $ok = headers_sent($file, $line);
  252. if ($ok && $throw && $this->headersSentThrowsException) {
  253. require_once 'Zend/Controller/Response/Exception.php';
  254. throw new Zend_Controller_Response_Exception('Cannot send headers; headers already sent in ' . $file . ', line ' . $line);
  255. }
  256. return !$ok;
  257. }
  258. /**
  259. * Send all headers
  260. *
  261. * Sends any headers specified. If an {@link setHttpResponseCode() HTTP response code}
  262. * has been specified, it is sent with the first header.
  263. *
  264. * @return Zend_Controller_Response_Abstract
  265. */
  266. public function sendHeaders()
  267. {
  268. // Only check if we can send headers if we have headers to send
  269. if (count($this->_headersRaw) || count($this->_headers) || (200 != $this->_httpResponseCode)) {
  270. $this->canSendHeaders(true);
  271. } elseif (200 == $this->_httpResponseCode) {
  272. // Haven't changed the response code, and we have no headers
  273. return $this;
  274. }
  275. $httpCodeSent = false;
  276. foreach ($this->_headersRaw as $header) {
  277. if (!$httpCodeSent && $this->_httpResponseCode) {
  278. header($header, true, $this->_httpResponseCode);
  279. $httpCodeSent = true;
  280. } else {
  281. header($header);
  282. }
  283. }
  284. foreach ($this->_headers as $header) {
  285. if (!$httpCodeSent && $this->_httpResponseCode) {
  286. header($header['name'] . ': ' . $header['value'], $header['replace'], $this->_httpResponseCode);
  287. $httpCodeSent = true;
  288. } else {
  289. header($header['name'] . ': ' . $header['value'], $header['replace']);
  290. }
  291. }
  292. if (!$httpCodeSent) {
  293. header('HTTP/1.1 ' . $this->_httpResponseCode);
  294. $httpCodeSent = true;
  295. }
  296. return $this;
  297. }
  298. /**
  299. * Set body content
  300. *
  301. * If $name is not passed, or is not a string, resets the entire body and
  302. * sets the 'default' key to $content.
  303. *
  304. * If $name is a string, sets the named segment in the body array to
  305. * $content.
  306. *
  307. * @param string $content
  308. * @param null|string $name
  309. * @return Zend_Controller_Response_Abstract
  310. */
  311. public function setBody($content, $name = null)
  312. {
  313. if ((null === $name) || !is_string($name)) {
  314. $this->_body = array('default' => (string) $content);
  315. } else {
  316. $this->_body[$name] = (string) $content;
  317. }
  318. return $this;
  319. }
  320. /**
  321. * Append content to the body content
  322. *
  323. * @param string $content
  324. * @param null|string $name
  325. * @return Zend_Controller_Response_Abstract
  326. */
  327. public function appendBody($content, $name = null)
  328. {
  329. if ((null === $name) || !is_string($name)) {
  330. if (isset($this->_body['default'])) {
  331. $this->_body['default'] .= (string) $content;
  332. } else {
  333. return $this->append('default', $content);
  334. }
  335. } elseif (isset($this->_body[$name])) {
  336. $this->_body[$name] .= (string) $content;
  337. } else {
  338. return $this->append($name, $content);
  339. }
  340. return $this;
  341. }
  342. /**
  343. * Clear body array
  344. *
  345. * With no arguments, clears the entire body array. Given a $name, clears
  346. * just that named segment; if no segment matching $name exists, returns
  347. * false to indicate an error.
  348. *
  349. * @param string $name Named segment to clear
  350. * @return boolean
  351. */
  352. public function clearBody($name = null)
  353. {
  354. if (null !== $name) {
  355. $name = (string) $name;
  356. if (isset($this->_body[$name])) {
  357. unset($this->_body[$name]);
  358. return true;
  359. }
  360. return false;
  361. }
  362. $this->_body = array();
  363. return true;
  364. }
  365. /**
  366. * Return the body content
  367. *
  368. * If $spec is false, returns the concatenated values of the body content
  369. * array. If $spec is boolean true, returns the body content array. If
  370. * $spec is a string and matches a named segment, returns the contents of
  371. * that segment; otherwise, returns null.
  372. *
  373. * @param boolean $spec
  374. * @return string|array|null
  375. */
  376. public function getBody($spec = false)
  377. {
  378. if (false === $spec) {
  379. ob_start();
  380. $this->outputBody();
  381. return ob_get_clean();
  382. } elseif (true === $spec) {
  383. return $this->_body;
  384. } elseif (is_string($spec) && isset($this->_body[$spec])) {
  385. return $this->_body[$spec];
  386. }
  387. return null;
  388. }
  389. /**
  390. * Append a named body segment to the body content array
  391. *
  392. * If segment already exists, replaces with $content and places at end of
  393. * array.
  394. *
  395. * @param string $name
  396. * @param string $content
  397. * @return Zend_Controller_Response_Abstract
  398. */
  399. public function append($name, $content)
  400. {
  401. if (!is_string($name)) {
  402. require_once 'Zend/Controller/Response/Exception.php';
  403. throw new Zend_Controller_Response_Exception('Invalid body segment key ("' . gettype($name) . '")');
  404. }
  405. if (isset($this->_body[$name])) {
  406. unset($this->_body[$name]);
  407. }
  408. $this->_body[$name] = (string) $content;
  409. return $this;
  410. }
  411. /**
  412. * Prepend a named body segment to the body content array
  413. *
  414. * If segment already exists, replaces with $content and places at top of
  415. * array.
  416. *
  417. * @param string $name
  418. * @param string $content
  419. * @return void
  420. */
  421. public function prepend($name, $content)
  422. {
  423. if (!is_string($name)) {
  424. require_once 'Zend/Controller/Response/Exception.php';
  425. throw new Zend_Controller_Response_Exception('Invalid body segment key ("' . gettype($name) . '")');
  426. }
  427. if (isset($this->_body[$name])) {
  428. unset($this->_body[$name]);
  429. }
  430. $new = array($name => (string) $content);
  431. $this->_body = $new + $this->_body;
  432. return $this;
  433. }
  434. /**
  435. * Insert a named segment into the body content array
  436. *
  437. * @param string $name
  438. * @param string $content
  439. * @param string $parent
  440. * @param boolean $before Whether to insert the new segment before or
  441. * after the parent. Defaults to false (after)
  442. * @return Zend_Controller_Response_Abstract
  443. */
  444. public function insert($name, $content, $parent = null, $before = false)
  445. {
  446. if (!is_string($name)) {
  447. require_once 'Zend/Controller/Response/Exception.php';
  448. throw new Zend_Controller_Response_Exception('Invalid body segment key ("' . gettype($name) . '")');
  449. }
  450. if ((null !== $parent) && !is_string($parent)) {
  451. require_once 'Zend/Controller/Response/Exception.php';
  452. throw new Zend_Controller_Response_Exception('Invalid body segment parent key ("' . gettype($parent) . '")');
  453. }
  454. if (isset($this->_body[$name])) {
  455. unset($this->_body[$name]);
  456. }
  457. if ((null === $parent) || !isset($this->_body[$parent])) {
  458. return $this->append($name, $content);
  459. }
  460. $ins = array($name => (string) $content);
  461. $keys = array_keys($this->_body);
  462. $loc = array_search($parent, $keys);
  463. if (!$before) {
  464. // Increment location if not inserting before
  465. ++$loc;
  466. }
  467. if (0 === $loc) {
  468. // If location of key is 0, we're prepending
  469. $this->_body = $ins + $this->_body;
  470. } elseif ($loc >= (count($this->_body))) {
  471. // If location of key is maximal, we're appending
  472. $this->_body = $this->_body + $ins;
  473. } else {
  474. // Otherwise, insert at location specified
  475. $pre = array_slice($this->_body, 0, $loc);
  476. $post = array_slice($this->_body, $loc);
  477. $this->_body = $pre + $ins + $post;
  478. }
  479. return $this;
  480. }
  481. /**
  482. * Echo the body segments
  483. *
  484. * @return void
  485. */
  486. public function outputBody()
  487. {
  488. $body = implode('', $this->_body);
  489. echo $body;
  490. }
  491. /**
  492. * Register an exception with the response
  493. *
  494. * @param Exception $e
  495. * @return Zend_Controller_Response_Abstract
  496. */
  497. public function setException(Exception $e)
  498. {
  499. $this->_exceptions[] = $e;
  500. return $this;
  501. }
  502. /**
  503. * Retrieve the exception stack
  504. *
  505. * @return array
  506. */
  507. public function getException()
  508. {
  509. return $this->_exceptions;
  510. }
  511. /**
  512. * Has an exception been registered with the response?
  513. *
  514. * @return boolean
  515. */
  516. public function isException()
  517. {
  518. return !empty($this->_exceptions);
  519. }
  520. /**
  521. * Does the response object contain an exception of a given type?
  522. *
  523. * @param string $type
  524. * @return boolean
  525. */
  526. public function hasExceptionOfType($type)
  527. {
  528. foreach ($this->_exceptions as $e) {
  529. if ($e instanceof $type) {
  530. return true;
  531. }
  532. }
  533. return false;
  534. }
  535. /**
  536. * Does the response object contain an exception with a given message?
  537. *
  538. * @param string $message
  539. * @return boolean
  540. */
  541. public function hasExceptionOfMessage($message)
  542. {
  543. foreach ($this->_exceptions as $e) {
  544. if ($message == $e->getMessage()) {
  545. return true;
  546. }
  547. }
  548. return false;
  549. }
  550. /**
  551. * Does the response object contain an exception with a given code?
  552. *
  553. * @param int $code
  554. * @return boolean
  555. */
  556. public function hasExceptionOfCode($code)
  557. {
  558. $code = (int) $code;
  559. foreach ($this->_exceptions as $e) {
  560. if ($code == $e->getCode()) {
  561. return true;
  562. }
  563. }
  564. return false;
  565. }
  566. /**
  567. * Retrieve all exceptions of a given type
  568. *
  569. * @param string $type
  570. * @return false|array
  571. */
  572. public function getExceptionByType($type)
  573. {
  574. $exceptions = array();
  575. foreach ($this->_exceptions as $e) {
  576. if ($e instanceof $type) {
  577. $exceptions[] = $e;
  578. }
  579. }
  580. if (empty($exceptions)) {
  581. $exceptions = false;
  582. }
  583. return $exceptions;
  584. }
  585. /**
  586. * Retrieve all exceptions of a given message
  587. *
  588. * @param string $message
  589. * @return false|array
  590. */
  591. public function getExceptionByMessage($message)
  592. {
  593. $exceptions = array();
  594. foreach ($this->_exceptions as $e) {
  595. if ($message == $e->getMessage()) {
  596. $exceptions[] = $e;
  597. }
  598. }
  599. if (empty($exceptions)) {
  600. $exceptions = false;
  601. }
  602. return $exceptions;
  603. }
  604. /**
  605. * Retrieve all exceptions of a given code
  606. *
  607. * @param mixed $code
  608. * @return void
  609. */
  610. public function getExceptionByCode($code)
  611. {
  612. $code = (int) $code;
  613. $exceptions = array();
  614. foreach ($this->_exceptions as $e) {
  615. if ($code == $e->getCode()) {
  616. $exceptions[] = $e;
  617. }
  618. }
  619. if (empty($exceptions)) {
  620. $exceptions = false;
  621. }
  622. return $exceptions;
  623. }
  624. /**
  625. * Whether or not to render exceptions (off by default)
  626. *
  627. * If called with no arguments or a null argument, returns the value of the
  628. * flag; otherwise, sets it and returns the current value.
  629. *
  630. * @param boolean $flag Optional
  631. * @return boolean
  632. */
  633. public function renderExceptions($flag = null)
  634. {
  635. if (null !== $flag) {
  636. $this->_renderExceptions = $flag ? true : false;
  637. }
  638. return $this->_renderExceptions;
  639. }
  640. /**
  641. * Send the response, including all headers, rendering exceptions if so
  642. * requested.
  643. *
  644. * @return void
  645. */
  646. public function sendResponse()
  647. {
  648. $this->sendHeaders();
  649. if ($this->isException() && $this->renderExceptions()) {
  650. $exceptions = '';
  651. foreach ($this->getException() as $e) {
  652. $exceptions .= $e->__toString() . "\n";
  653. }
  654. echo $exceptions;
  655. return;
  656. }
  657. $this->outputBody();
  658. }
  659. /**
  660. * Magic __toString functionality
  661. *
  662. * Proxies to {@link sendResponse()} and returns response value as string
  663. * using output buffering.
  664. *
  665. * @return string
  666. */
  667. public function __toString()
  668. {
  669. ob_start();
  670. $this->sendResponse();
  671. return ob_get_clean();
  672. }
  673. }