<?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\module\testimonials
 * @copyright Copyright (c) 2012 - 2017 clearFusionCMS. All rights reserved.
 * @link http://clearfusioncms.com
 */

/**
 * testimonialsPublicController Class
 *
 * Public controller.
 *
 * @package clearFusionCMS\module\testimonials
 */
class testimonialsPublicController extends cfContentController {

	/**
	 * Route to testimonials page.
	 *
	 * @var flRouterRoute
	 */
	protected $testimonialRoute = null;

	/**
	 * The database table name.
	 *
	 * @var string
	 */
	protected $tableName;

	/**
	 * Action to show the testimonial page/archive.
	 *
	 * @throws flExceptionNotFound
	 */
	function archiveAction() {
		$this->tableName = 'cf_testimonials_' . clearFusionCMS::getSite();

		cfContentFilter::useTemplateEngine($tpl = new cfTemplateEngine($this));

		$imageRoute = $this->content->getContainerRoute($this->pageData['id'], 'images/:size/:id', array(), array('size' => '[tsml]', 'id' => '\d+'), '.*');
		$this->testimonialRoute = $this->content->getContainerRoute($this->pageData['id'], 'testimonial/:id', array(), array('id' => '\d+'));
		$homeRoute = $this->content->getContainerRoute($this->pageData['id'], ':marker/:page', array('marker' => 'page', 'page' => '0'), array('marker' => 'page', 'page' => '\d+'));

		// If match for an image
		if(($params = $imageRoute->match($this->request->getSegments())) && preg_match('/^(png|jpg|gif)$/', $params['extension'])) {

			// Get the name of the file
			$hashID = md5($params['id']);
			$fileCfg = clearFusionCMS::getSiteConfig('cfSystemFileStore');
			$baseName = $fileCfg->privateStorage . '/testimonials/' . clearFusionCMS::getSite() . "/$hashID[0]/$hashID[1]/$hashID";
			$fileName = $baseName . "_$params[size].$params[extension]";

			// If file not readable then we need to generate it
			if(!is_readable($fileName)) {
				$baseName .= '.' . $params['extension'];

				// If base file not present or not published then we're done
				if(!is_readable($baseName) || !$this->db->fetchOne("SELECT published FROM $this->tableName WHERE id=?", $params['id']))
					throw new flExceptionNotFound();

				// Get the size information
				$cfg = clearFusionCMS::getSiteConfig('cfTestimonials');
				$w = $cfg->get($params['size'] . 'w');
				$h = $cfg->get($params['size'] . 'h');

				// Scale and cache
				$img = new flImage($baseName);
				if($cfg->get($params['size'] . 'crop'))
					$img->resizeCrop($w, $h);
				else
					$img->resize($w, $h);
				$img->save($fileName);
			}

			// Send the file out
			$this->response->setContentType(flMimeTypes::getType($params['extension']))
				->compressOutput(false)
				->setHeader('Content-Disposition', 'inline; filename=' . basename($fileName))
				->setLastModified(filemtime($fileName))
				->sendHeaders();

			if(isset($img))
				$img->output();
			else
				readfile($fileName);
		}
		else {
			// If match for testimonial
			if($requestParams = $this->testimonialRoute->match($this->request->getSegments())) {
				if(!($pageData = clearFusionCMS::getCache()->get($cacheID = '_cf_testimonialsPage' . $this->request->getSelf()))) {
					$this->pageData['module'] = 'testimonials';
					$this->pageData['contentid'] = $requestParams['id'];
					$this->pageData['content'] = $tpl->getChunk('testimonials.testimonial');

					$testimonial = $this->db->fetchRow("SELECT id,dateoftestimonial,gender,age,fileext,author,location,occupation,website,testimonial,published,company FROM $this->tableName WHERE id=?", $requestParams['id']);
					if($testimonial && $testimonial['published']) {
						$cfg = clearFusionCMS::getSiteConfig('cfTestimonials');

						$g = new flDate($testimonial['dateoftestimonial'] . ' UTC', clearFusionCMS::getSysTimezone());
						$g = $g->toString(flDate::DATE);
						$this->pageData['customfields']['dategiven'] = $g;
						$this->pageData['customfields']['gender'] = $testimonial['gender'] == 'm' ? __('Male', 'testimonials') : __('Female', 'testimonials');
						$this->pageData['customfields']['age'] = $testimonial['age'];
						$this->pageData['customfields']['author'] = $testimonial['author'];
						$this->pageData['customfields']['location'] = $testimonial['location'];
						$this->pageData['customfields']['occupation'] = $testimonial['occupation'];
						$this->pageData['customfields']['company'] = $testimonial['company'];
						$this->pageData['customfields']['website'] = $testimonial['website'];
						$this->pageData['customfields']['testimonial'] = cfContentFilter::apply($cfg->get('filter', ''), $testimonial['testimonial']);
						$this->pageData['customfields']['testimonialURI'] = $this->testimonialRoute->assemble(array('id' => $testimonial['id']), true);
						$this->pageData['customfields']['testimonialDate'] = sprintf(__('Date of Testimonial: %s', 'testimonials'), $g);
						$this->pageData['customfields']['permaLinkLabel'] = __('Perma Link', 'testimonials');
					} else
						throw new flExceptionNotFound();

					clearFusionCMS::getCache()->store($cacheID, $this->pageData);
				}
				else
					$this->pageData = $pageData;
			}
			// Treat page as a virtual page for paging through products
			else if(count($this->pageData['childpath']) && !$homeRoute->match($this->request->getSegments())) {
				throw new flExceptionNotFound();
			}

			// Render the page
			if(!$this->content->renderPage($tpl, $this->pageData))
				throw new flExceptionNotFound();
		}
	}

	/**
	 * 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) {
		$breadcrumb = parent::getBreadcrumb($id);

		// If request is for this page then continue
		if($this->pageData['module'] == 'testimonials' && ($testimonial = $this->db->fetchRow("SELECT author FROM $this->tableName WHERE id=?", $this->pageData['contentid']))) {
			$breadcrumb->addCrumb($testimonial['author'], $this->testimonialRoute->assemble(array('id' => $this->pageData['contentid'])));
		}

		return $breadcrumb;
	}
}
