<?php
/************************************************************************
 * This file is part of EspoCRM.
 *
 * EspoCRM - Open Source CRM application.
 * Copyright (C) 2014  Yuri Kuznetsov, Taras Machyshyn, Oleksiy Avramenko
 * Website: http://www.espocrm.com
 *
 * EspoCRM is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * EspoCRM is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with EspoCRM. If not, see http://www.gnu.org/licenses/.
 ************************************************************************/

namespace Espo\Core\Utils\Api;


class Slim extends \Slim\Slim
{

	/**
	 * Redefine the run method
	 *
	 * We no need to use a Slim handler
	 */
	public function run()
	{
		//set_error_handler(array('\Slim\Slim', 'handleErrors')); //Espo: no needs to use this handler

		//Apply final outer middleware layers
		if ($this->config('debug')) {
			//Apply pretty exceptions only in debug to avoid accidental information leakage in production
			//$this->add(new \Slim\Middleware\PrettyExceptions()); //Espo: no needs to use this handler
		}

		//Invoke middleware and application stack
		$this->middleware[0]->call();

		//Fetch status, header, and body
		list($status, $headers, $body) = $this->response->finalize();

		// Serialize cookies (with optional encryption)
		\Slim\Http\Util::serializeCookies($headers, $this->response->cookies, $this->settings);

		//Send headers
		if (headers_sent() === false) {
			//Send status
			if (strpos(PHP_SAPI, 'cgi') === 0) {
				header(sprintf('Status: %s', \Slim\Http\Response::getMessageForCode($status)));
			} else {
				header(sprintf('HTTP/%s %s', $this->config('http.version'), \Slim\Http\Response::getMessageForCode($status)));
			}

			//Send headers
			foreach ($headers as $name => $value) {
				$hValues = explode("\n", $value);
				foreach ($hValues as $hVal) {
					header("$name: $hVal", false);
				}
			}
		}

		//Send body, but only if it isn't a HEAD request
		if (!$this->request->isHead()) {
			echo $body;
		}

		//restore_error_handler(); //Espo: no needs to use this handler
	}

	public function printError($error, $status)
	{
		echo static::generateTemplateMarkup($status, '<p>'.$error.'</p><a href="' . $this->request->getRootUri() . '/">Visit the Home Page</a>');
	}


}