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-2008 Zend Technologies USA Inc. (http://www.zend.com)
  18. * @license http://framework.zend.com/license/new-bsd New BSD License
  19. */
  20. /**
  21. * Zend_Controller_Response_Abstract
  22. *
  23. * Base class for Zend_Controller responses
  24. *
  25. * @package Zend_Controller
  26. * @subpackage Response
  27. * @copyright Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
  28. * @license http://framework.zend.com/license/new-bsd New BSD License
  29. */
  30. abstract class Zend_Controller_Response_Abstract
  31. {
  32. /**
  33. * Body content
  34. * @var array
  35. */
  36. protected $_body = array();
  37. /**
  38. * Exception stack
  39. * @var Exception
  40. */
  41. protected $_exceptions = array();
  42. /**
  43. * Array of headers. Each header is an array with keys 'name' and 'value'
  44. * @var array
  45. */
  46. protected $_headers = array();
  47. /**
  48. * Array of raw headers. Each header is a single string, the entire header to emit
  49. * @var array
  50. */
  51. protected $_headersRaw = array();
  52. /**
  53. * HTTP response code to use in headers
  54. * @var int
  55. */
  56. protected $_httpResponseCode = 200;
  57. /**
  58. * Flag; is this response a redirect?
  59. * @var boolean
  60. */
  61. protected $_isRedirect = false;
  62. /**
  63. * Whether or not to render exceptions; off by default
  64. * @var boolean
  65. */
  66. protected $_renderExceptions = false;
  67. /**
  68. * Flag; if true, when header operations are called after headers have been
  69. * sent, an exception will be raised; otherwise, processing will continue
  70. * as normal. Defaults to true.
  71. *
  72. * @see canSendHeaders()
  73. * @var boolean
  74. */
  75. public $headersSentThrowsException = true;
  76. /**
  77. * Normalize a header name
  78. *
  79. * Normalizes a header name to X-Capitalized-Names
  80. *
  81. * @param string $name
  82. * @return string
  83. */
  84. protected function _normalizeHeader($name)
  85. {
  86. $filtered = str_replace(array('-', '_'), ' ', (string) $name);
  87. $filtered = ucwords(strtolower($filtered));
  88. $filtered = str_replace(' ', '-', $filtered);
  89. return $filtered;
  90. }
  91. /**
  92. * Set a header
  93. *
  94. * If $replace is true, replaces any headers already defined with that
  95. * $name.
  96. *
  97. * @param string $name
  98. * @param string $value
  99. * @param boolean $replace
  100. * @return Zend_Controller_Response_Abstract
  101. */
  102. public function setHeader($name, $value, $replace = false)
  103. {
  104. $this->canSendHeaders(true);
  105. $name = $this->_normalizeHeader($name);
  106. $value = (string) $value;
  107. if ($replace) {
  108. foreach ($this->_headers as $key => $header) {
  109. if ($name == $header['name']) {
  110. unset($this->_headers[$key]);
  111. }
  112. }
  113. }
  114. $this->_headers[] = array(
  115. 'name' => $name,
  116. 'value' => $value,
  117. 'replace' => $replace
  118. );
  119. return $this;
  120. }
  121. /**
  122. * Set redirect URL
  123. *
  124. * Sets Location header and response code. Forces replacement of any prior
  125. * redirects.
  126. *
  127. * @param string $url
  128. * @param int $code
  129. * @return Zend_Controller_Response_Abstract
  130. */
  131. public function setRedirect($url, $code = 302)
  132. {
  133. $this->canSendHeaders(true);
  134. $this->setHeader('Location', $url, true)
  135. ->setHttpResponseCode($code);
  136. return $this;
  137. }
  138. /**
  139. * Is this a redirect?
  140. *
  141. * @return boolean
  142. */
  143. public function isRedirect()
  144. {
  145. return $this->_isRedirect;
  146. }
  147. /**
  148. * Return array of headers; see {@link $_headers} for format
  149. *
  150. * @return array
  151. */
  152. public function getHeaders()
  153. {
  154. return $this->_headers;
  155. }
  156. /**
  157. * Clear headers
  158. *
  159. * @return Zend_Controller_Response_Abstract
  160. */
  161. public function clearHeaders()
  162. {
  163. $this->_headers = array();
  164. return $this;
  165. }
  166. /**
  167. * Set raw HTTP header
  168. *
  169. * Allows setting non key => value headers, such as status codes
  170. *
  171. * @param string $value
  172. * @return Zend_Controller_Response_Abstract
  173. */
  174. public function setRawHeader($value)
  175. {
  176. $this->canSendHeaders(true);
  177. if ('Location' == substr($value, 0, 8)) {
  178. $this->_isRedirect = true;
  179. }
  180. $this->_headersRaw[] = (string) $value;
  181. return $this;
  182. }
  183. /**
  184. * Retrieve all {@link setRawHeader() raw HTTP headers}
  185. *
  186. * @return array
  187. */
  188. public function getRawHeaders()
  189. {
  190. return $this->_headersRaw;
  191. }
  192. /**
  193. * Clear all {@link setRawHeader() raw HTTP headers}
  194. *
  195. * @return Zend_Controller_Response_Abstract
  196. */
  197. public function clearRawHeaders()
  198. {
  199. $this->_headersRaw = array();
  200. return $this;
  201. }
  202. /**
  203. * Clear all headers, normal and raw
  204. *
  205. * @return Zend_Controller_Response_Abstract
  206. */
  207. public function clearAllHeaders()
  208. {
  209. return $this->clearHeaders()
  210. ->clearRawHeaders();
  211. }
  212. /**
  213. * Set HTTP response code to use with headers
  214. *
  215. * @param int $code
  216. * @return Zend_Controller_Response_Abstract
  217. */
  218. public function setHttpResponseCode($code)
  219. {
  220. if (!is_int($code) || (100 > $code) || (599 < $code)) {
  221. require_once 'Zend/Controller/Response/Exception.php';
  222. throw new Zend_Controller_Response_Exception('Invalid HTTP response code');
  223. }
  224. if ((300 <= $code) && (307 >= $code)) {
  225. $this->_isRedirect = true;
  226. } else {
  227. $this->_isRedirect = false;
  228. }
  229. $this->_httpResponseCode = $code;
  230. return $this;
  231. }
  232. /**
  233. * Retrieve HTTP response code
  234. *
  235. * @return int
  236. */
  237. public function getHttpResponseCode()
  238. {
  239. return $this->_httpResponseCode;
  240. }
  241. /**
  242. * Can we send headers?
  243. *
  244. * @param boolean $throw Whether or not to throw an exception if headers have been sent; defaults to false
  245. * @return boolean
  246. * @throws Zend_Controller_Response_Exception
  247. */
  248. public function canSendHeaders($throw = false)
  249. {
  250. $ok = headers_sent($file, $line);
  251. if ($ok && $throw && $this->headersSentThrowsException) {
  252. require_once 'Zend/Controller/Response/Exception.php';
  253. throw new Zend_Controller_Response_Exception('Cannot send headers; headers already sent in ' . $file . ', line ' . $line);
  254. }
  255. return !$ok;
  256. }
  257. /**
  258. * Send all headers
  259. *
  260. * Sends any headers specified. If an {@link setHttpResponseCode() HTTP response code}
  261. * has been specified, it is sent with the first header.
  262. *
  263. * @return Zend_Controller_Response_Abstract
  264. */
  265. public function sendHeaders()
  266. {
  267. // Only check if we can send headers if we have headers to send
  268. if (count($this->_headersRaw) || count($this->_headers) || (200 != $this->_httpResponseCode)) {
  269. $this->canSendHeaders(true);
  270. } elseif (200 == $this->_httpResponseCode) {
  271. // Haven't changed the response code, and we have no headers
  272. return $this;
  273. }
  274. $httpCodeSent = false;
  275. foreach ($this->_headersRaw as $header) {
  276. if (!$httpCodeSent && $this->_httpResponseCode) {
  277. header($header, true, $this->_httpResponseCode);
  278. $httpCodeSent = true;
  279. } else {
  280. header($header);
  281. }
  282. }
  283. foreach ($this->_headers as $header) {
  284. if (!$httpCodeSent && $this->_httpResponseCode) {
  285. header($header['name'] . ': ' . $header['value'], $header['replace'], $this->_httpResponseCode);
  286. $httpCodeSent = true;
  287. } else {
  288. header($header['name'] . ': ' . $header['value'], $header['replace']);
  289. }
  290. }
  291. if (!$httpCodeSent) {
  292. header('HTTP/1.1 ' . $this->_httpResponseCode);
  293. $httpCodeSent = true;
  294. }
  295. return $this;
  296. }
  297. /**
  298. * Set body content
  299. *
  300. * If $name is not passed, or is not a string, resets the entire body and
  301. * sets the 'default' key to $content.
  302. *
  303. * If $name is a string, sets the named segment in the body array to
  304. * $content.
  305. *
  306. * @param string $content
  307. * @param null|string $name
  308. * @return Zend_Controller_Response_Abstract
  309. */
  310. public function setBody($content, $name = null)
  311. {
  312. if ((null === $name) || !is_string($name)) {
  313. $this->_body = array('default' => (string) $content);
  314. } else {
  315. $this->_body[$name] = (string) $content;
  316. }
  317. return $this;
  318. }
  319. /**
  320. * Append content to the body content
  321. *
  322. * @param string $content
  323. * @param null|string $name
  324. * @return Zend_Controller_Response_Abstract
  325. */
  326. public function appendBody($content, $name = null)
  327. {
  328. if ((null === $name) || !is_string($name)) {
  329. if (isset($this->_body['default'])) {
  330. $this->_body['default'] .= (string) $content;
  331. } else {
  332. return $this->append('default', $content);
  333. }
  334. } elseif (isset($this->_body[$name])) {
  335. $this->_body[$name] .= (string) $content;
  336. } else {
  337. return $this->append($name, $content);
  338. }
  339. return $this;
  340. }
  341. /**
  342. * Clear body array
  343. *
  344. * With no arguments, clears the entire body array. Given a $name, clears
  345. * just that named segment; if no segment matching $name exists, returns
  346. * false to indicate an error.
  347. *
  348. * @param string $name Named segment to clear
  349. * @return boolean
  350. */
  351. public function clearBody($name = null)
  352. {
  353. if (null !== $name) {
  354. $name = (string) $name;
  355. if (isset($this->_body[$name])) {
  356. unset($this->_body[$name]);
  357. return true;
  358. }
  359. return false;
  360. }
  361. $this->_body = array();
  362. return true;
  363. }
  364. /**
  365. * Return the body content
  366. *
  367. * If $spec is false, returns the concatenated values of the body content
  368. * array. If $spec is boolean true, returns the body content array. If
  369. * $spec is a string and matches a named segment, returns the contents of
  370. * that segment; otherwise, returns null.
  371. *
  372. * @param boolean $spec
  373. * @return string|array|null
  374. */
  375. public function getBody($spec = false)
  376. {
  377. if (false === $spec) {
  378. ob_start();
  379. $this->outputBody();
  380. return ob_get_clean();
  381. } elseif (true === $spec) {
  382. return $this->_body;
  383. } elseif (is_string($spec) && isset($this->_body[$spec])) {
  384. return $this->_body[$spec];
  385. }
  386. return null;
  387. }
  388. /**
  389. * Append a named body segment to the body content array
  390. *
  391. * If segment already exists, replaces with $content and places at end of
  392. * array.
  393. *
  394. * @param string $name
  395. * @param string $content
  396. * @return Zend_Controller_Response_Abstract
  397. */
  398. public function append($name, $content)
  399. {
  400. if (!is_string($name)) {
  401. require_once 'Zend/Controller/Response/Exception.php';
  402. throw new Zend_Controller_Response_Exception('Invalid body segment key ("' . gettype($name) . '")');
  403. }
  404. if (isset($this->_body[$name])) {
  405. unset($this->_body[$name]);
  406. }
  407. $this->_body[$name] = (string) $content;
  408. return $this;
  409. }
  410. /**
  411. * Prepend a named body segment to the body content array
  412. *
  413. * If segment already exists, replaces with $content and places at top of
  414. * array.
  415. *
  416. * @param string $name
  417. * @param string $content
  418. * @return void
  419. */
  420. public function prepend($name, $content)
  421. {
  422. if (!is_string($name)) {
  423. require_once 'Zend/Controller/Response/Exception.php';
  424. throw new Zend_Controller_Response_Exception('Invalid body segment key ("' . gettype($name) . '")');
  425. }
  426. if (isset($this->_body[$name])) {
  427. unset($this->_body[$name]);
  428. }
  429. $new = array($name => (string) $content);
  430. $this->_body = $new + $this->_body;
  431. return $this;
  432. }
  433. /**
  434. * Insert a named segment into the body content array
  435. *
  436. * @param string $name
  437. * @param string $content
  438. * @param string $parent
  439. * @param boolean $before Whether to insert the new segment before or
  440. * after the parent. Defaults to false (after)
  441. * @return Zend_Controller_Response_Abstract
  442. */
  443. public function insert($name, $content, $parent = null, $before = false)
  444. {
  445. if (!is_string($name)) {
  446. require_once 'Zend/Controller/Response/Exception.php';
  447. throw new Zend_Controller_Response_Exception('Invalid body segment key ("' . gettype($name) . '")');
  448. }
  449. if ((null !== $parent) && !is_string($parent)) {
  450. require_once 'Zend/Controller/Response/Exception.php';
  451. throw new Zend_Controller_Response_Exception('Invalid body segment parent key ("' . gettype($parent) . '")');
  452. }
  453. if (isset($this->_body[$name])) {
  454. unset($this->_body[$name]);
  455. }
  456. if ((null === $parent) || !isset($this->_body[$parent])) {
  457. return $this->append($name, $content);
  458. }
  459. $ins = array($name => (string) $content);
  460. $keys = array_keys($this->_body);
  461. $loc = array_search($parent, $keys);
  462. if (!$before) {
  463. // Increment location if not inserting before
  464. ++$loc;
  465. }
  466. if (0 === $loc) {
  467. // If location of key is 0, we're prepending
  468. $this->_body = $ins + $this->_body;
  469. } elseif ($loc >= (count($this->_body))) {
  470. // If location of key is maximal, we're appending
  471. $this->_body = $this->_body + $ins;
  472. } else {
  473. // Otherwise, insert at location specified
  474. $pre = array_slice($this->_body, 0, $loc);
  475. $post = array_slice($this->_body, $loc);
  476. $this->_body = $pre + $ins + $post;
  477. }
  478. return $this;
  479. }
  480. /**
  481. * Echo the body segments
  482. *
  483. * @return void
  484. */
  485. public function outputBody()
  486. {
  487. foreach ($this->_body as $content) {
  488. echo $content;
  489. }
  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. }