Abstract.php 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794
  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-2010 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-2010 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. * Clears the specified HTTP header
  169. *
  170. * @param string $name
  171. * @return Zend_Controller_Response_Abstract
  172. */
  173. public function clearHeader($name)
  174. {
  175. if (! count($this->_headers)) {
  176. return $this;
  177. }
  178. foreach ($this->_headers as $index => $header) {
  179. if ($name == $header['name']) {
  180. unset($this->_headers[$index]);
  181. }
  182. }
  183. return $this;
  184. }
  185. /**
  186. * Set raw HTTP header
  187. *
  188. * Allows setting non key => value headers, such as status codes
  189. *
  190. * @param string $value
  191. * @return Zend_Controller_Response_Abstract
  192. */
  193. public function setRawHeader($value)
  194. {
  195. $this->canSendHeaders(true);
  196. if ('Location' == substr($value, 0, 8)) {
  197. $this->_isRedirect = true;
  198. }
  199. $this->_headersRaw[] = (string) $value;
  200. return $this;
  201. }
  202. /**
  203. * Retrieve all {@link setRawHeader() raw HTTP headers}
  204. *
  205. * @return array
  206. */
  207. public function getRawHeaders()
  208. {
  209. return $this->_headersRaw;
  210. }
  211. /**
  212. * Clear all {@link setRawHeader() raw HTTP headers}
  213. *
  214. * @return Zend_Controller_Response_Abstract
  215. */
  216. public function clearRawHeaders()
  217. {
  218. $this->_headersRaw = array();
  219. return $this;
  220. }
  221. /**
  222. * Clears the specified raw HTTP header
  223. *
  224. * @param string $headerRaw
  225. * @return Zend_Controller_Response_Abstract
  226. */
  227. public function clearRawHeader($headerRaw)
  228. {
  229. if (! count($this->_headersRaw)) {
  230. return $this;
  231. }
  232. $key = array_search($headerRaw, $this->_headersRaw);
  233. unset($this->_headersRaw[$key]);
  234. return $this;
  235. }
  236. /**
  237. * Clear all headers, normal and raw
  238. *
  239. * @return Zend_Controller_Response_Abstract
  240. */
  241. public function clearAllHeaders()
  242. {
  243. return $this->clearHeaders()
  244. ->clearRawHeaders();
  245. }
  246. /**
  247. * Set HTTP response code to use with headers
  248. *
  249. * @param int $code
  250. * @return Zend_Controller_Response_Abstract
  251. */
  252. public function setHttpResponseCode($code)
  253. {
  254. if (!is_int($code) || (100 > $code) || (599 < $code)) {
  255. require_once 'Zend/Controller/Response/Exception.php';
  256. throw new Zend_Controller_Response_Exception('Invalid HTTP response code');
  257. }
  258. if ((300 <= $code) && (307 >= $code)) {
  259. $this->_isRedirect = true;
  260. } else {
  261. $this->_isRedirect = false;
  262. }
  263. $this->_httpResponseCode = $code;
  264. return $this;
  265. }
  266. /**
  267. * Retrieve HTTP response code
  268. *
  269. * @return int
  270. */
  271. public function getHttpResponseCode()
  272. {
  273. return $this->_httpResponseCode;
  274. }
  275. /**
  276. * Can we send headers?
  277. *
  278. * @param boolean $throw Whether or not to throw an exception if headers have been sent; defaults to false
  279. * @return boolean
  280. * @throws Zend_Controller_Response_Exception
  281. */
  282. public function canSendHeaders($throw = false)
  283. {
  284. $ok = headers_sent($file, $line);
  285. if ($ok && $throw && $this->headersSentThrowsException) {
  286. require_once 'Zend/Controller/Response/Exception.php';
  287. throw new Zend_Controller_Response_Exception('Cannot send headers; headers already sent in ' . $file . ', line ' . $line);
  288. }
  289. return !$ok;
  290. }
  291. /**
  292. * Send all headers
  293. *
  294. * Sends any headers specified. If an {@link setHttpResponseCode() HTTP response code}
  295. * has been specified, it is sent with the first header.
  296. *
  297. * @return Zend_Controller_Response_Abstract
  298. */
  299. public function sendHeaders()
  300. {
  301. // Only check if we can send headers if we have headers to send
  302. if (count($this->_headersRaw) || count($this->_headers) || (200 != $this->_httpResponseCode)) {
  303. $this->canSendHeaders(true);
  304. } elseif (200 == $this->_httpResponseCode) {
  305. // Haven't changed the response code, and we have no headers
  306. return $this;
  307. }
  308. $httpCodeSent = false;
  309. foreach ($this->_headersRaw as $header) {
  310. if (!$httpCodeSent && $this->_httpResponseCode) {
  311. header($header, true, $this->_httpResponseCode);
  312. $httpCodeSent = true;
  313. } else {
  314. header($header);
  315. }
  316. }
  317. foreach ($this->_headers as $header) {
  318. if (!$httpCodeSent && $this->_httpResponseCode) {
  319. header($header['name'] . ': ' . $header['value'], $header['replace'], $this->_httpResponseCode);
  320. $httpCodeSent = true;
  321. } else {
  322. header($header['name'] . ': ' . $header['value'], $header['replace']);
  323. }
  324. }
  325. if (!$httpCodeSent) {
  326. header('HTTP/1.1 ' . $this->_httpResponseCode);
  327. $httpCodeSent = true;
  328. }
  329. return $this;
  330. }
  331. /**
  332. * Set body content
  333. *
  334. * If $name is not passed, or is not a string, resets the entire body and
  335. * sets the 'default' key to $content.
  336. *
  337. * If $name is a string, sets the named segment in the body array to
  338. * $content.
  339. *
  340. * @param string $content
  341. * @param null|string $name
  342. * @return Zend_Controller_Response_Abstract
  343. */
  344. public function setBody($content, $name = null)
  345. {
  346. if ((null === $name) || !is_string($name)) {
  347. $this->_body = array('default' => (string) $content);
  348. } else {
  349. $this->_body[$name] = (string) $content;
  350. }
  351. return $this;
  352. }
  353. /**
  354. * Append content to the body content
  355. *
  356. * @param string $content
  357. * @param null|string $name
  358. * @return Zend_Controller_Response_Abstract
  359. */
  360. public function appendBody($content, $name = null)
  361. {
  362. if ((null === $name) || !is_string($name)) {
  363. if (isset($this->_body['default'])) {
  364. $this->_body['default'] .= (string) $content;
  365. } else {
  366. return $this->append('default', $content);
  367. }
  368. } elseif (isset($this->_body[$name])) {
  369. $this->_body[$name] .= (string) $content;
  370. } else {
  371. return $this->append($name, $content);
  372. }
  373. return $this;
  374. }
  375. /**
  376. * Clear body array
  377. *
  378. * With no arguments, clears the entire body array. Given a $name, clears
  379. * just that named segment; if no segment matching $name exists, returns
  380. * false to indicate an error.
  381. *
  382. * @param string $name Named segment to clear
  383. * @return boolean
  384. */
  385. public function clearBody($name = null)
  386. {
  387. if (null !== $name) {
  388. $name = (string) $name;
  389. if (isset($this->_body[$name])) {
  390. unset($this->_body[$name]);
  391. return true;
  392. }
  393. return false;
  394. }
  395. $this->_body = array();
  396. return true;
  397. }
  398. /**
  399. * Return the body content
  400. *
  401. * If $spec is false, returns the concatenated values of the body content
  402. * array. If $spec is boolean true, returns the body content array. If
  403. * $spec is a string and matches a named segment, returns the contents of
  404. * that segment; otherwise, returns null.
  405. *
  406. * @param boolean $spec
  407. * @return string|array|null
  408. */
  409. public function getBody($spec = false)
  410. {
  411. if (false === $spec) {
  412. ob_start();
  413. $this->outputBody();
  414. return ob_get_clean();
  415. } elseif (true === $spec) {
  416. return $this->_body;
  417. } elseif (is_string($spec) && isset($this->_body[$spec])) {
  418. return $this->_body[$spec];
  419. }
  420. return null;
  421. }
  422. /**
  423. * Append a named body segment to the body content array
  424. *
  425. * If segment already exists, replaces with $content and places at end of
  426. * array.
  427. *
  428. * @param string $name
  429. * @param string $content
  430. * @return Zend_Controller_Response_Abstract
  431. */
  432. public function append($name, $content)
  433. {
  434. if (!is_string($name)) {
  435. require_once 'Zend/Controller/Response/Exception.php';
  436. throw new Zend_Controller_Response_Exception('Invalid body segment key ("' . gettype($name) . '")');
  437. }
  438. if (isset($this->_body[$name])) {
  439. unset($this->_body[$name]);
  440. }
  441. $this->_body[$name] = (string) $content;
  442. return $this;
  443. }
  444. /**
  445. * Prepend a named body segment to the body content array
  446. *
  447. * If segment already exists, replaces with $content and places at top of
  448. * array.
  449. *
  450. * @param string $name
  451. * @param string $content
  452. * @return void
  453. */
  454. public function prepend($name, $content)
  455. {
  456. if (!is_string($name)) {
  457. require_once 'Zend/Controller/Response/Exception.php';
  458. throw new Zend_Controller_Response_Exception('Invalid body segment key ("' . gettype($name) . '")');
  459. }
  460. if (isset($this->_body[$name])) {
  461. unset($this->_body[$name]);
  462. }
  463. $new = array($name => (string) $content);
  464. $this->_body = $new + $this->_body;
  465. return $this;
  466. }
  467. /**
  468. * Insert a named segment into the body content array
  469. *
  470. * @param string $name
  471. * @param string $content
  472. * @param string $parent
  473. * @param boolean $before Whether to insert the new segment before or
  474. * after the parent. Defaults to false (after)
  475. * @return Zend_Controller_Response_Abstract
  476. */
  477. public function insert($name, $content, $parent = null, $before = false)
  478. {
  479. if (!is_string($name)) {
  480. require_once 'Zend/Controller/Response/Exception.php';
  481. throw new Zend_Controller_Response_Exception('Invalid body segment key ("' . gettype($name) . '")');
  482. }
  483. if ((null !== $parent) && !is_string($parent)) {
  484. require_once 'Zend/Controller/Response/Exception.php';
  485. throw new Zend_Controller_Response_Exception('Invalid body segment parent key ("' . gettype($parent) . '")');
  486. }
  487. if (isset($this->_body[$name])) {
  488. unset($this->_body[$name]);
  489. }
  490. if ((null === $parent) || !isset($this->_body[$parent])) {
  491. return $this->append($name, $content);
  492. }
  493. $ins = array($name => (string) $content);
  494. $keys = array_keys($this->_body);
  495. $loc = array_search($parent, $keys);
  496. if (!$before) {
  497. // Increment location if not inserting before
  498. ++$loc;
  499. }
  500. if (0 === $loc) {
  501. // If location of key is 0, we're prepending
  502. $this->_body = $ins + $this->_body;
  503. } elseif ($loc >= (count($this->_body))) {
  504. // If location of key is maximal, we're appending
  505. $this->_body = $this->_body + $ins;
  506. } else {
  507. // Otherwise, insert at location specified
  508. $pre = array_slice($this->_body, 0, $loc);
  509. $post = array_slice($this->_body, $loc);
  510. $this->_body = $pre + $ins + $post;
  511. }
  512. return $this;
  513. }
  514. /**
  515. * Echo the body segments
  516. *
  517. * @return void
  518. */
  519. public function outputBody()
  520. {
  521. $body = implode('', $this->_body);
  522. echo $body;
  523. }
  524. /**
  525. * Register an exception with the response
  526. *
  527. * @param Exception $e
  528. * @return Zend_Controller_Response_Abstract
  529. */
  530. public function setException(Exception $e)
  531. {
  532. $this->_exceptions[] = $e;
  533. return $this;
  534. }
  535. /**
  536. * Retrieve the exception stack
  537. *
  538. * @return array
  539. */
  540. public function getException()
  541. {
  542. return $this->_exceptions;
  543. }
  544. /**
  545. * Has an exception been registered with the response?
  546. *
  547. * @return boolean
  548. */
  549. public function isException()
  550. {
  551. return !empty($this->_exceptions);
  552. }
  553. /**
  554. * Does the response object contain an exception of a given type?
  555. *
  556. * @param string $type
  557. * @return boolean
  558. */
  559. public function hasExceptionOfType($type)
  560. {
  561. foreach ($this->_exceptions as $e) {
  562. if ($e instanceof $type) {
  563. return true;
  564. }
  565. }
  566. return false;
  567. }
  568. /**
  569. * Does the response object contain an exception with a given message?
  570. *
  571. * @param string $message
  572. * @return boolean
  573. */
  574. public function hasExceptionOfMessage($message)
  575. {
  576. foreach ($this->_exceptions as $e) {
  577. if ($message == $e->getMessage()) {
  578. return true;
  579. }
  580. }
  581. return false;
  582. }
  583. /**
  584. * Does the response object contain an exception with a given code?
  585. *
  586. * @param int $code
  587. * @return boolean
  588. */
  589. public function hasExceptionOfCode($code)
  590. {
  591. $code = (int) $code;
  592. foreach ($this->_exceptions as $e) {
  593. if ($code == $e->getCode()) {
  594. return true;
  595. }
  596. }
  597. return false;
  598. }
  599. /**
  600. * Retrieve all exceptions of a given type
  601. *
  602. * @param string $type
  603. * @return false|array
  604. */
  605. public function getExceptionByType($type)
  606. {
  607. $exceptions = array();
  608. foreach ($this->_exceptions as $e) {
  609. if ($e instanceof $type) {
  610. $exceptions[] = $e;
  611. }
  612. }
  613. if (empty($exceptions)) {
  614. $exceptions = false;
  615. }
  616. return $exceptions;
  617. }
  618. /**
  619. * Retrieve all exceptions of a given message
  620. *
  621. * @param string $message
  622. * @return false|array
  623. */
  624. public function getExceptionByMessage($message)
  625. {
  626. $exceptions = array();
  627. foreach ($this->_exceptions as $e) {
  628. if ($message == $e->getMessage()) {
  629. $exceptions[] = $e;
  630. }
  631. }
  632. if (empty($exceptions)) {
  633. $exceptions = false;
  634. }
  635. return $exceptions;
  636. }
  637. /**
  638. * Retrieve all exceptions of a given code
  639. *
  640. * @param mixed $code
  641. * @return void
  642. */
  643. public function getExceptionByCode($code)
  644. {
  645. $code = (int) $code;
  646. $exceptions = array();
  647. foreach ($this->_exceptions as $e) {
  648. if ($code == $e->getCode()) {
  649. $exceptions[] = $e;
  650. }
  651. }
  652. if (empty($exceptions)) {
  653. $exceptions = false;
  654. }
  655. return $exceptions;
  656. }
  657. /**
  658. * Whether or not to render exceptions (off by default)
  659. *
  660. * If called with no arguments or a null argument, returns the value of the
  661. * flag; otherwise, sets it and returns the current value.
  662. *
  663. * @param boolean $flag Optional
  664. * @return boolean
  665. */
  666. public function renderExceptions($flag = null)
  667. {
  668. if (null !== $flag) {
  669. $this->_renderExceptions = $flag ? true : false;
  670. }
  671. return $this->_renderExceptions;
  672. }
  673. /**
  674. * Send the response, including all headers, rendering exceptions if so
  675. * requested.
  676. *
  677. * @return void
  678. */
  679. public function sendResponse()
  680. {
  681. $this->sendHeaders();
  682. if ($this->isException() && $this->renderExceptions()) {
  683. $exceptions = '';
  684. foreach ($this->getException() as $e) {
  685. $exceptions .= $e->__toString() . "\n";
  686. }
  687. echo $exceptions;
  688. return;
  689. }
  690. $this->outputBody();
  691. }
  692. /**
  693. * Magic __toString functionality
  694. *
  695. * Proxies to {@link sendResponse()} and returns response value as string
  696. * using output buffering.
  697. *
  698. * @return string
  699. */
  700. public function __toString()
  701. {
  702. ob_start();
  703. $this->sendResponse();
  704. return ob_get_clean();
  705. }
  706. }