Abstract.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756
  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. foreach ($this->_body as $content) {
  489. echo $content;
  490. }
  491. }
  492. /**
  493. * Register an exception with the response
  494. *
  495. * @param Exception $e
  496. * @return Zend_Controller_Response_Abstract
  497. */
  498. public function setException(Exception $e)
  499. {
  500. $this->_exceptions[] = $e;
  501. return $this;
  502. }
  503. /**
  504. * Retrieve the exception stack
  505. *
  506. * @return array
  507. */
  508. public function getException()
  509. {
  510. return $this->_exceptions;
  511. }
  512. /**
  513. * Has an exception been registered with the response?
  514. *
  515. * @return boolean
  516. */
  517. public function isException()
  518. {
  519. return !empty($this->_exceptions);
  520. }
  521. /**
  522. * Does the response object contain an exception of a given type?
  523. *
  524. * @param string $type
  525. * @return boolean
  526. */
  527. public function hasExceptionOfType($type)
  528. {
  529. foreach ($this->_exceptions as $e) {
  530. if ($e instanceof $type) {
  531. return true;
  532. }
  533. }
  534. return false;
  535. }
  536. /**
  537. * Does the response object contain an exception with a given message?
  538. *
  539. * @param string $message
  540. * @return boolean
  541. */
  542. public function hasExceptionOfMessage($message)
  543. {
  544. foreach ($this->_exceptions as $e) {
  545. if ($message == $e->getMessage()) {
  546. return true;
  547. }
  548. }
  549. return false;
  550. }
  551. /**
  552. * Does the response object contain an exception with a given code?
  553. *
  554. * @param int $code
  555. * @return boolean
  556. */
  557. public function hasExceptionOfCode($code)
  558. {
  559. $code = (int) $code;
  560. foreach ($this->_exceptions as $e) {
  561. if ($code == $e->getCode()) {
  562. return true;
  563. }
  564. }
  565. return false;
  566. }
  567. /**
  568. * Retrieve all exceptions of a given type
  569. *
  570. * @param string $type
  571. * @return false|array
  572. */
  573. public function getExceptionByType($type)
  574. {
  575. $exceptions = array();
  576. foreach ($this->_exceptions as $e) {
  577. if ($e instanceof $type) {
  578. $exceptions[] = $e;
  579. }
  580. }
  581. if (empty($exceptions)) {
  582. $exceptions = false;
  583. }
  584. return $exceptions;
  585. }
  586. /**
  587. * Retrieve all exceptions of a given message
  588. *
  589. * @param string $message
  590. * @return false|array
  591. */
  592. public function getExceptionByMessage($message)
  593. {
  594. $exceptions = array();
  595. foreach ($this->_exceptions as $e) {
  596. if ($message == $e->getMessage()) {
  597. $exceptions[] = $e;
  598. }
  599. }
  600. if (empty($exceptions)) {
  601. $exceptions = false;
  602. }
  603. return $exceptions;
  604. }
  605. /**
  606. * Retrieve all exceptions of a given code
  607. *
  608. * @param mixed $code
  609. * @return void
  610. */
  611. public function getExceptionByCode($code)
  612. {
  613. $code = (int) $code;
  614. $exceptions = array();
  615. foreach ($this->_exceptions as $e) {
  616. if ($code == $e->getCode()) {
  617. $exceptions[] = $e;
  618. }
  619. }
  620. if (empty($exceptions)) {
  621. $exceptions = false;
  622. }
  623. return $exceptions;
  624. }
  625. /**
  626. * Whether or not to render exceptions (off by default)
  627. *
  628. * If called with no arguments or a null argument, returns the value of the
  629. * flag; otherwise, sets it and returns the current value.
  630. *
  631. * @param boolean $flag Optional
  632. * @return boolean
  633. */
  634. public function renderExceptions($flag = null)
  635. {
  636. if (null !== $flag) {
  637. $this->_renderExceptions = $flag ? true : false;
  638. }
  639. return $this->_renderExceptions;
  640. }
  641. /**
  642. * Send the response, including all headers, rendering exceptions if so
  643. * requested.
  644. *
  645. * @return void
  646. */
  647. public function sendResponse()
  648. {
  649. $this->sendHeaders();
  650. if ($this->isException() && $this->renderExceptions()) {
  651. $exceptions = '';
  652. foreach ($this->getException() as $e) {
  653. $exceptions .= $e->__toString() . "\n";
  654. }
  655. echo $exceptions;
  656. return;
  657. }
  658. $this->outputBody();
  659. }
  660. /**
  661. * Magic __toString functionality
  662. *
  663. * Proxies to {@link sendResponse()} and returns response value as string
  664. * using output buffering.
  665. *
  666. * @return string
  667. */
  668. public function __toString()
  669. {
  670. ob_start();
  671. $this->sendResponse();
  672. return ob_get_clean();
  673. }
  674. }