<?php

/**
 * THIS SOFTWARE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED
 * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
 *
 * @package clearFusionCMS
 * @copyright Copyright (c) 2012 - 2017 clearFusionCMS. All rights reserved.
 * @link http://clearfusioncms.com
 */

/**
 * errorController Class
 *
 * Custom error controller to route errors through the selected error page if present.
 *
 * @package clearFusionCMS
 */
class errorController extends flExceptionErrorController {
	/**
	 * The content object.
	 *
	 * @var cfContent
	 */
	public $content;

	/**
	 * The raw page data held in the database.
	 *
	 * @var array
	 */
	public $pageData = null;

	/**
	 * The error action.
	 */
	function errorAction() {

		// Look up site
		if($this->request && ($siteData = flApp::getDb()->fetchRow('SELECT shortname,displayname,twitterusername,puressl FROM cf_sites WHERE domain=?', $this->request->getServerName()))) {
			$siteName = $siteData['displayname'];
			$site = $siteData['shortname'];
			clearFusionCMS::setSite($site, $siteName, $siteData['twitterusername'], $siteData['puressl']);

			// Create the content and template engine objects
			$this->content = new cfContent(flApp::getDb(), $site);

			// Get and draw the error page
			if($data = $this->content->getPage($this->content->getErrorPage($this->getException()->getCode()))) {
				clearFusionCMS::disableCache();

				$data['customfields']['error_code'] = $this->getException()->getCode();
				$data['customfields']['error_name'] = $this->getException()->getName();
				$data['customfields']['error_message'] = nl2br(fusionLib::htmlChars($this->getMessage()));
				$data['module'] = '';
				$data['contentid'] = '';
				$data['container_extra'] = '';

				if($this->content->renderPage(new cfTemplateEngine($this), $this->pageData = $data, $this->request->getSelf() . '#error' . $this->getException()->getCode()))
					return;
			}
		}

		parent::errorAction();
    }

	/**
	 * Build a breadcrumb trail.
	 *
	 * @param int $id The id of the page to get the trail to, null for current.
	 * @return flWidgetBreadcrumb The breadcrumb widget.
	 */
	function getBreadcrumb($id = null) {
		$breadcrub = new flWidgetBreadcrumb();

		$first = true;
		$path = $this->content->getPath($id === null ? $this->pageData['id'] : $id, array('id', 'title', 'menutitle'));
		foreach($path as $seg) {
			if($first && $seg['id'] != ($def = $this->content->getDefaultPage()) && $def) {
				$d = $this->content->getNodeData($def, array('title', 'menutitle'));
				$breadcrub->addCrumb(empty($d['menutitle']) ? $d['title'] : $d['menutitle'], $this->content->getPageURI($def));
			}
			$breadcrub->addCrumb(empty($seg['menutitle']) ? $seg['title'] : $seg['menutitle'], $this->content->getPageURI($seg['id']));
			$first = false;
		}

		return $breadcrub;
	}
}
