<?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
 */

/**
 * testimonialsBackendController Class
 *
 * Backend controller for editing managing testimonials.
 *
 * @package clearFusionCMS\module\testimonials
 */
class testimonialsBackendController extends cfBackendController {

	/**
	 * Render the page.
	 *
	 * @param string $content The page content.
	 */
	function renderAdminPage($content) {

		// Create the toolbar
		$fam = new flWidgetFloatingActionMenu();
		$fam->addAction('add', __('Add Testimonial', 'testimonialsBackend'), $this->assemble('testimonials', 'add'));

		$this->tpl->registerChunk('fam', $fam->render());

		$rootTree = new flWidgetTreeView();

		// Build tree of albums
		$tree = new flWidgetTreeView();
		$results = $this->db->query('SELECT id,author FROM cf_testimonials_' . clearFusionCMS::getSite() . ' WHERE !published ORDER BY dateoftestimonial ASC LIMIT 100');
		while($row = $results->fetch()) {
			$tree->addNode(new flWidgetTreeLinkNode($row['author'], $this->assemble('testimonials', 'edit', array($row['id'])), flWidgetTreeNode::DOC));
		}

		$rootTree->addNode($results->numRows() ? new flWidgetTreeChildNode(__('Unpublished Testimonials', 'testimonialsBackend'), $tree, null) : new flWidgetTreeNode(__('Unpublished Testimonials', 'testimonialsBackend'), flWidgetTreeNode::CONTAINER));

		// Render the page
		$this->renderPage(__('Testimonials', 'testimonialsBackend'), $content, $this->renderBlock('', $rootTree->render($this->tpl->getCodeBuffer())));
	}

	/**
	 * Dashboard action.
	 */
	function dashboardAction() {
		$this->testPermission('cfTestimonials.post');
		$this->breadcrumbTrail->addCrumb(__('Testimonials', 'testimonialsBackend'), $this->assemble('testimonials', 'dashboard'));

		$content = '';

		// Router to build pagination with
		$paginationRoute = new flRouterRoute(str_replace(array(':module', ':action', '*'), array('testimonials', 'dashboard', ':page'), (string)$this->router->getRoute('cfManagerModule')), array('page' => '0'), array('page' => '\d+'), $this->request);
		$route = new flRouterRoute(':page', array('page' => '0'), array('page' => '\d+'));
		if($params = $route->match($this->request->getParam('*', array()))) {

			$numItems = $this->db->fetchOne('SELECT COUNT(*) FROM cf_testimonials_' . clearFusionCMS::getSite());
			$pagination = new flWidgetPagination($params['page'], $numItems);
			$pagination->setRoute($paginationRoute, array(), 'page');

			$results = $this->db->fetchAll('SELECT id,author,dateoftestimonial FROM cf_testimonials_' . clearFusionCMS::getSite() . ' ORDER BY dateoftestimonial DESC LIMIT ' . $pagination->getStart() . ',' . $pagination->getRows());
			if(count($results)) {
				$table = new flWidgetTable();
				$table->setClass('tablewidget bordered striped rowhover responsive')
					->setHeadings(__('ID', 'testimonialsBackend'), __('Author Name', 'testimonialsBackend'), __('Date of Testimonial', 'testimonialsBackend'), __('Operation', 'testimonialsBackend'))
					->setColData('id', 'author', 'dateoftestimonial', 'ops')
					->skipEncode('ops', 'dateoftestimonial');

				foreach($results as $item) {
					$t = new flDate($item['dateoftestimonial'] . ' UTC', clearFusionCMS::getSysTimezone());
					$item['dateoftestimonial'] = $t->toString('%d %M %Y %O');;
					$item['ops'] = "<a href=\"" . $this->assemble('testimonials', 'edit', array($item['id'])) . "\">" . __('Edit', 'testimonialsBackend') . "</a>";
					$table->addRow($item);
				}

				$content = $table->render();
			}

			$content .= sprintf(__("<p>Found: %d testimonials.</p>", 'testimonialsBackend'), $numItems);

			$this->renderAdminPage($this->renderBlock(__('Existing Testimonials', 'testimonialsBackend'), $content, '', '', $pagination->render()));
		}
		else
			$this->response->redirectTo($this->assemble('testimonials', 'dashboard', array(), true));
	}

	/**
	 * Add testimonial action.
	 */
	function addAction() {
		$this->testPermission('cfTestimonials.post');
		$this->breadcrumbTrail->addCrumb(__('Testimonials', 'testimonialsBackend'), $this->assemble('testimonials', 'dashboard'));
		$this->breadcrumbTrail->addCrumb(__('Add Testimonial', 'testimonialsBackend'), $this->assemble('testimonials', 'add'));

		$form = new flForm($this->request, 'contentform', $this->assemble('testimonials', 'add'), true);
		$form->setCSS('metaSSubmit');

		$name = new flFormElementText($form, 'name');
		$name->setLabel(__('Name', 'testimonialsBackend'))
			->setDescription(__('Name of testimonial author, &#91;&#91;+author&#93;&#93;', 'testimonialsBackend'))
			->setRequired()
			->addValidator(new flFormValidatorRequired())
			->addValidator(new flFormValidatorMaxLength(255));

		$gender = new flFormElementSelect($form, 'gender', null, array('m' => __('Male', 'testimonialsBackend'), 'f' => __('Female', 'testimonialsBackend')));
		$gender->setLabel(__('Gender', 'testimonialsBackend'))
			->setDescription(__('The gender of the testimonial author, &#91;&#91;+gender&#93;&#93;', 'testimonialsBackend'));

		$age = new flFormElementInteger($form, 'age');
		$age->setLabel(__('Age', 'testimonialsBackend'))
			->setDescription(__('The age of the author, &#91;&#91;+age&#93;&#93;', 'testimonialsBackend'));

		$company = new flFormElementText($form, 'company');
		$company->setLabel(__('Company', 'testimonialsBackend'))
			->setDescription(__('Testimonial authors company, &#91;&#91;+company&#93;&#93;', 'testimonialsBackend'))
			->addValidator(new flFormValidatorMaxLength(255));

		$occupation = new flFormElementText($form, 'occupation');
		$occupation->setLabel(__('Occupation', 'testimonialsBackend'))
			->setDescription(__('Testimonial authors occupation, &#91;&#91;+occupation&#93;&#93;', 'testimonialsBackend'))
			->addValidator(new flFormValidatorMaxLength(255));

		$location = new flFormElementText($form, 'location');
		$location->setLabel(__('Location', 'testimonialsBackend'))
			->setDescription(__('Location of testimonial author, &#91;&#91;+location&#93;&#93;', 'testimonialsBackend'))
			->addValidator(new flFormValidatorMaxLength(255));

		$email = new flFormElementEmail($form, 'email');
		$email->setLabel(__('Email', 'testimonialsBackend'))
			->addValidator(new flFormValidatorMaxLength(255));

		$web = new flFormElementUri($form, 'uri');
		$web->setLabel(__('Website', 'testimonialsBackend'))
			->setDescription(__('Testimonial authors website, &#91;&#91;+website&#93;&#93;', 'testimonialsBackend'))
			->addValidator(new flFormValidatorMaxLength(255));

		// Capture ctrl+s for save
		$this->tpl->getCodeBuffer()->bufferHeadJS('system/app/js/cfMetaS.js');
		$this->confirmLeavePage();

		$cfgTest = clearFusionCMS::getSiteConfig('cfTestimonials');
		if($cfgTest->get('htmlEditor', true)) {
			$ctnt = cfEditor::create(
				$this->getEditorModule($cfgTest->get('editor', '')),
				$form,
				'testimonial',
				''
			);
			$ctnt->setLabel(__('Testimonial (HTML)', 'testimonialsBackend'))
				->setRequired()
				->addValidator(new flFormValidatorRequired())
				->setDescription(__('The testimonial, &#91;&#91;+testimonial&#93;&#93;', 'testimonialsBackend'))
				->addValidator(new flFormValidatorMaxLength(2097152));
		}
		else {
			$ctnt = cfEditor::create(
				$this->getCodeEditorModule(),
				$form,
				'testimonial',
				''
			);
			$ctnt->setLabel(__('Testimonial', 'testimonialsBackend'))
				->setRequired()
				->addValidator(new flFormValidatorRequired())
				->addValidator(new flFormValidatorMaxLength(2097152))
				->editorContentType('textwrap');
		}

		$imgFile = new flFormElementFile($form, 'imgfile');
		$imgFile->setLabel(__('Upload an Image', 'testimonialsBackend'))->setCSS('primary');

		$imgURI = new flFormElementUri($form, 'imguri');
		$imgURI->setLabel(__('Download and Use Image', 'testimonialsBackend'));

		$tags = new flFormElementText($form, 'tags');
		$tags->setLabel(__('Tags', 'testimonialsBackend'))
			->addValidator(new flFormValidatorMaxLength(255))
			->setDescription(__('Comma separated list of tags.', 'testimonialsBackend'));

		$_testiDate = new flDate(null, clearFusionCMS::getSysTimezone());

		$tz = flDateTzMenu::get();

		$testiDate = new flFormElementText($form, 'testidate', $_testiDate->toString(flDate::DATETIMESHORT));
		$testiDate->setLabel(__('Date of Testimonial (year-month-day hh:mm)', 'testimonialsBackend'))
			->setRequired()
			->setDescription($this->alertMessage('Info', sprintf(__('All dates are %s.', 'testimonialsBackend'), $tz[clearFusionCMS::getSysTimezone()])))
			->addValidator(new flFormValidatorRequired())
			->addValidator(new flFormValidatorRegex('/^\d{4}-(0?[0-9]|1[0-2])-\d{1,2} \d{1,2}:\d{1,2}$/', __('The date must be in the form yyyy-mm-dd hh:mm.', 'testimonialsBackend')));

		$publish = new flFormElementCheckbox($form, 'publish', 1);
		$publish->setLabel(__('Publish Testimonial', 'testimonialsBackend'));

		$submit = new flFormElementSubmit($form, 'create');
		$submit->setCaption(__('Create Testimonial', 'testimonialsBackend'))->setCSS('primary');

		$form->groupElements('leftcolauthorinfo', array($name, $gender, $age, $email, $publish))
			->groupElements('rightcolauthorinfo', array($company, $occupation, $location, $web, $tags))
			->groupElements('leftcolimage', array($imgFile, $imgURI))
			->groupElements('content', array($ctnt, $testiDate))
			->groupElements('submit', array($submit), new flFormDecoratorList(new flFormDecoratorDl()))
			->addTab(__('Author', 'testimonialsBackend'), array('leftcolauthorinfo', 'rightcolauthorinfo', 'content'))
			->addTab(__('Image', 'testimonialsBackend'), array('leftcolimage'));

		$form->focusElement($name);

		$msg = '';
		if($form->isSubmitted() && $form->isValid()) {
			// Convert the dates to UTC
			$_testiDate = new flDate($testiDate->getValue(), clearFusionCMS::getSysTimezone());
			$_testiDate->setTimezone('UTC');

			// Create testimonial
			if($this->db->insert('cf_testimonials_' . clearFusionCMS::getSite(), $d = array(
				'gender' => $gender->getValue(),
				'age' => $age->getValue() ? $age->getValue() : 0,
				'dateoftestimonial' => $_testiDate->toString(),
				'tags' => $tags->getValue(),
				'author' => $name->getValue(),
				'email' => $email->getValue(),
				'location' => $location->getValue(),
				'company' => $company->getValue(),
				'occupation' => $occupation->getValue(),
				'website' => $web->getValue(),
				'testimonial' => $ctnt->getValue(),
				'published' => $publish->getValue(),
				'fileext' => ''
			))) {
				$id = $this->db->insertID();

				testimonialsAudit::create($id, $name->getValue());

				// If upload file given
				if($imgFile->fileUploaded() && ($fileName = $this->getFilename($id))) {
					$imgFile->moveTo($fileName);
				}
				// Else if download file give
				else if($imgURI->getValue() != '' && ($fileName = $this->getFilename($id))) {

					// Get the image from a remote source
					$http = new flHttpClient($imgURI->getValue());
					if($http->sendRequest() && $http->getResponseCode() == 200) {
						// Save the file data
						@file_put_contents($fileName, $http->getBody());
						unset($http); // Release the object & memory
					}
				}

				// File file present then resize and remember it's extension
				if(isset($fileName) && is_readable($fileName)) {
					try {
						$img = new flImage($fileName);
						switch($img->getType()) {
							case IMAGETYPE_GIF: $ext = '.gif'; break;
							case IMAGETYPE_JPEG: $ext = '.jpg'; break;
							case IMAGETYPE_PNG: $ext = '.png'; break;
							default: throw new flImageException('Unknown image type.');
						}
						$this->db->update('cf_testimonials_' . clearFusionCMS::getSite(), array('fileext' => $ext), 'id=?', $id);
						@rename($fileName, $fileName . $ext);
					} catch(flException $e) {
						@unlink($fileName);
					}
				}

				// Send to search if published and flush cache
				if($publish->getValue()) {
					clearFusionCMS::getEventManager()->notify(new flEvent('system.searchIndex', array(
						'path' => array('testimonials', $id),
						'accessPerm' => '',
						'publishedAt' => $d['dateoftestimonial'],
						'fields' => array(
							'testimonial.author' => $d['author'],
							'testimonial.body' => $d['testimonial'],
							'testimonial.tags' => $d['tags']
						))));

					$this->cache->flush();
				}

				$this->session->flashSet('cfManagerOpSuccess', $this->alertMessage('Success', __('The new testimonial has been created.', 'testimonialsBackend')));
				$this->response->redirectTo($this->assemble('testimonials', 'edit', array($id), true));
			}
			else
				$msg = $this->alertMessage('Error', __('Unable to create the testimonial, please try again.', 'testimonialsBackend'));

			$e = $this->db->errorString();
		}

		$content = $this->renderBlock(__('Add Testimonial', 'testimonialsBackend'), $form->render($this->tpl->getCodeBuffer()), '', $msg);

		$this->renderAdminPage($content);
	}

	/**
	 * Get the thumb of the testimonial image.
	 *
	 * @throws flExceptionNotFound
	 */
	function thumbnailAction() {
		$this->testPermission('cfTestimonials.post');

		$route = new flRouterRoute(':id', array(), array('id' => '\d+'));
		if($params = $route->match($this->request->getParam('*', array()))) {
			if($ext = $this->db->fetchOne('SELECT fileext FROM cf_testimonials_' . clearFusionCMS::getSite() . ' WHERE id=?', $params['id'])) {
				$cfg = clearFusionCMS::getSiteConfig('cfSystemFileStore');
				$hashId = md5($params['id']);
				$file = $cfg->privateStorage . '/testimonials/' . clearFusionCMS::getSite() . "/$hashId[0]/$hashId[1]/$hashId$ext";

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

				$img = new flImage($file);
				$img->resizeCrop(150, 150);
				$img->output();
			}
			else
				throw new flExceptionNotFound();
		}
		else
			throw new flExceptionNotFound();
	}

	/**
	 * Edit testimonial action.
	 */
	function editAction() {
		$this->testPermission('cfTestimonials.post');
		$this->breadcrumbTrail->addCrumb(__('Testimonials', 'testimonialsBackend'), $this->assemble('testimonials', 'dashboard'));
		$this->breadcrumbTrail->addCrumb(__('Edit Testimonial', 'testimonialsBackend'), $this->assemble('testimonial', 'edit'));

		$content = '';
		$msg = $this->session->flashGet('cfManagerOpSuccess') ? $this->session->flashGet('cfManagerOpSuccess') : '';

		$route = new flRouterRoute(':id', array(), array('id' => '\d+'));
		if($params = $route->match($this->request->getParam('*', array()))) {
			if(($content = $this->lockObject('testimonials', $params['id'])) === true && ($data = $this->db->fetchRow('SELECT * FROM cf_testimonials_' . clearFusionCMS::getSite() . ' WHERE id=?', $params['id']))) {

				$form = new flForm($this->request, 'contentform', $this->assemble('testimonials', 'edit', array($params['id'])), true);
				$form->setCSS('metaSSubmit');

				$name = new flFormElementText($form, 'name', $data['author']);
				$name->setLabel(__('Name', 'testimonialsBackend'))
					->setDescription(__('Name of testimonial author, &#91;&#91;+author&#93;&#93;', 'testimonialsBackend'))
					->setRequired()
					->addValidator(new flFormValidatorRequired())
					->addValidator(new flFormValidatorMaxLength(255));

				$gender = new flFormElementSelect($form, 'gender', $data['gender'], array('m' => 'Male', 'f' => 'Female'));
				$gender->setLabel(__('Gender', 'testimonialsBackend'))
					->setDescription(__('The gender of the testimonial author, &#91;&#91;+gender&#93;&#93;', 'testimonialsBackend'));

				$age = new flFormElementInteger($form, 'age', null, null, $data['age']);
				$age->setLabel(__('Age', 'testimonialsBackend'))
					->setDescription(__('The age of the author, &#91;&#91;+age&#93;&#93;', 'testimonialsBackend'));

				$company = new flFormElementText($form, 'company', $data['company']);
				$company->setLabel(__('Company', 'testimonialsBackend'))
					->setDescription(__('Testimonial authors company, &#91;&#91;+company&#93;&#93;', 'testimonialsBackend'))
					->addValidator(new flFormValidatorMaxLength(255));

				$occupation = new flFormElementText($form, 'occupation', $data['occupation']);
				$occupation->setLabel(__('Occupation', 'testimonialsBackend'))
					->setDescription(__('Testimonial authors occupation, &#91;&#91;+occupation&#93;&#93;', 'testimonialsBackend'))
					->addValidator(new flFormValidatorMaxLength(255));

				$location = new flFormElementText($form, 'location', $data['location']);
				$location->setLabel(__('Location', 'testimonialsBackend'))
					->setDescription(__('Location of testimonial author, &#91;&#91;+location&#93;&#93;', 'testimonialsBackend'))
					->addValidator(new flFormValidatorMaxLength(255));

				$email = new flFormElementEmail($form, 'email', $data['email']);
				$email->setLabel(__('Email', 'testimonialsBackend'))
					->addValidator(new flFormValidatorMaxLength(255));

				$web = new flFormElementUri($form, 'uri', $data['website']);
				$web->setLabel(__('Website', 'testimonialsBackend'))
					->setDescription(__('Testimonial authors website, &#91;&#91;+website&#93;&#93;', 'testimonialsBackend'))
					->addValidator(new flFormValidatorMaxLength(255));

				// Capture ctrl+s for save
				$this->tpl->getCodeBuffer()->bufferHeadJS('system/app/js/cfMetaS.js');
				$this->confirmLeavePage();

				$cfgTest = clearFusionCMS::getSiteConfig('cfTestimonials');
				if($cfgTest->get('htmlEditor', true)) {
					$ctnt = cfEditor::create(
						$this->getEditorModule($cfgTest->get('editor', '')),
						$form,
						'testimonial',
						$data['testimonial']
					);
					$ctnt->setLabel(__('Testimonial (HTML)', 'testimonialsBackend'))
						->setRequired()
						->addValidator(new flFormValidatorRequired())
						->setDescription(__('The testimonial, &#91;&#91;+testimonial&#93;&#93;', 'testimonialsBackend'))
						->addValidator(new flFormValidatorMaxLength(2097152));
				}
				else {
					$ctnt = cfEditor::create(
						$this->getCodeEditorModule(),
						$form,
						'testimonial',
						$data['testimonial']
					);
					$ctnt->setLabel(__('Testimonial', 'testimonialsBackend'))
						->setRequired()
						->addValidator(new flFormValidatorRequired())
						->addValidator(new flFormValidatorMaxLength(2097152))
						->setRows(20)
						->editorContentType('textwrap');
				}

				$imgFile = new flFormElementFile($form, 'imgfile');
				$imgFile->setLabel(__('Upload an Image', 'testimonialsBackend'))->setCSS('primary');

				$imgPane = new flFormElementPane($form, 'imgthumb', empty($data['fileext']) ? 'None' : '<img src="' . $this->assemble('testimonials', 'thumbnail', array($data['id'])) . '" width="150" height="150" />');
				$imgPane->setLabel(__('The Current Image', 'testimonialsBackend'));

				$imgURI = new flFormElementUri($form, 'imguri');
				$imgURI->setLabel(__('Download and Use Image', 'testimonialsBackend'));

				$imgRemove = new flFormElementCheckbox($form, 'imgdel');
				$imgRemove->setLabel(__('Remove Image from Testimonial', 'testimonialsBackend'));

				$tags = new flFormElementText($form, 'tags', $data['tags']);
				$tags->setLabel('Tags')
					->addValidator(new flFormValidatorMaxLength(255))
					->setDescription(__('Comma separated list of tags.', 'testimonialsBackend'));

				$_testiDate = new flDate($data['dateoftestimonial'] . ' UTC', clearFusionCMS::getSysTimezone());

				$tz = flDateTzMenu::get();

				$testiDate = new flFormElementText($form, 'testidate', $_testiDate->toString(flDate::DATETIMESHORT));
				$testiDate->setLabel(__('Date of Testimonial (year-month-day hh:mm)', 'testimonialsBackend'))
					->setRequired()
					->setDescription($this->alertMessage('Info', sprintf(__('All dates are %s.', 'testimonialsBackend'), $tz[clearFusionCMS::getSysTimezone()])))
					->addValidator(new flFormValidatorRequired())
					->addValidator(new flFormValidatorRegex('/^\d{4}-(0?[0-9]|1[0-2])-\d{1,2} \d{1,2}:\d{1,2}$/', __('The date must be in the form yyyy-mm-dd hh:mm.', 'testimonialsBackend')));

				$publish = new flFormElementCheckbox($form, 'publish', $data['published']);
				$publish->setLabel(__('Publish Testimonial', 'testimonialsBackend'));

				$submit = new flFormElementSubmit($form, 'create');
				$submit->setCaption(__('Update Testimonial', 'testimonialsBackend'))->setCSS('primary');

				$del = new flFormElementSubmit($form, 'delete');
				$del->setCaption(__('Delete Testimonial', 'testimonialsBackend'))
					->setCSS('danger');

				$form->groupElements('leftcolauthorinfo', array($name, $gender, $age, $email, $publish))
					->groupElements('rightcolauthorinfo', array($company, $occupation, $location, $web, $tags))
					->groupElements('leftcolimage', array($imgFile, $imgURI))
					->groupElements('rightcolimage', array($imgPane, $imgRemove))
					->groupElements('content', array($ctnt, $testiDate))
					->groupElements('submit', array($submit, $del), new flFormDecoratorList(new flFormDecoratorDl()))
					->addTab(__('Author', 'testimonialsBackend'), array('leftcolauthorinfo', 'rightcolauthorinfo', 'content'))
					->addTab(__('Image', 'testimonialsBackend'), array('leftcolimage', 'rightcolimage'));

				$form->focusElement($name);

				if($form->isSubmitted() && $form->isValid()) {

					// If remove thumbnail
					if($imgRemove->getValue()) {
						$this->getFilename($data['id']);
						$this->db->update('cf_testimonials_' . clearFusionCMS::getSite(), array('fileext' => ''), 'id=?', $data['id']);
					}
					// Else if upload file given
					if($imgFile->fileUploaded() && ($fileName = $this->getFilename($data['id']))) {
						$imgFile->moveTo($fileName);
					}
					// Else if download file give
					else if($imgURI->getValue() != '' && ($fileName = $this->getFilename($data['id']))) {

						// Get the image from a remote source
						$http = new flHttpClient($imgURI->getValue());
						if($http->sendRequest() && $http->getResponseCode() == 200) {
							// Save the file data
							@file_put_contents($fileName, $http->getBody());
							unset($http); // Release the object & memory
						}
					}

					// File present then resize and remember it
					if(isset($fileName) && is_readable($fileName)) {
						try {
							$img = new flImage($fileName);
							switch($img->getType()) {
								case IMAGETYPE_GIF: $ext = '.gif'; break;
								case IMAGETYPE_JPEG: $ext = '.jpg'; break;
								case IMAGETYPE_PNG: $ext = '.png'; break;
								default: throw new flImageException('Unknown image type.');
							}
							$this->db->update('cf_testimonials_' . clearFusionCMS::getSite(), array('fileext' => $ext), 'id=?', $data['id']);
							@rename($fileName, $fileName . $ext);
						} catch(flException $e) {
							@unlink($fileName);
							$this->db->update('cf_testimonials_' . clearFusionCMS::getSite(), array('fileext' => ''), 'id=?', $data['id']);
						}

						// Purge the caches
						$content = new cfContent($this->db, clearFusionCMS::getSite());
						if(!empty($ext) && ($container = $content->getContainer('testimonials.archive'))) {
							$route = $content->getContainerRoute($container, 'images/:size/:id', array(), array(), $ext);

							clearFusionCMS::getEventManager()->notify(new flEvent('system.cachePurge', array('files' => array(
								$route->assemble(array('size' => 't', 'id' => $params['id'])),
								$route->assemble(array('size' => 's', 'id' => $params['id'])),
								$route->assemble(array('size' => 'm', 'id' => $params['id'])),
								$route->assemble(array('size' => 'l', 'id' => $params['id']))
							))));
						}
					}

					// Convert the dates to UTC
					$_testiDate = new flDate($testiDate->getValue(), clearFusionCMS::getSysTimezone());
					$_testiDate->setTimezone('UTC');

					if($del->getValue())
						$this->response->redirectTo($this->assemble('testimonials', 'delete', array($params['id']), true));

					// Delete from search
					clearFusionCMS::getEventManager()->notify(new flEvent('system.searchDelete', array(
						'path' => array('testimonials', $data['id'])
					)));

					// Make update data
					$d = array(
						'gender' => $gender->getValue(),
						'age' => $age->getValue(),
						'dateoftestimonial' => $_testiDate->toString(),
						'tags' => $tags->getValue(),
						'author' => $name->getValue(),
						'email' => $email->getValue(),
						'location' => $location->getValue(),
						'company' => $company->getValue(),
						'occupation' => $occupation->getValue(),
						'website' => $web->getValue(),
						'testimonial' => $ctnt->getValue(),
						'published' => $publish->getValue()
					);

					// Update the news item
					if($this->db->update('cf_testimonials_' . clearFusionCMS::getSite(), $d, 'id=?', $params['id'])) {
						testimonialsAudit::update($params['id'], $name->getValue(), $data);

						// Send to search if published
						if($publish->getValue()) {
							clearFusionCMS::getEventManager()->notify(new flEvent('system.searchIndex', array(
								'path' => array('testimonials', $params['id']),
								'accessPerm' => '',
								'publishedAt' => $d['dateoftestimonial'],
								'fields' => array(
									'testimonial.author' => $d['author'],
									'testimonial.body' => $d['testimonial'],
									'testimonial.tags' => $d['tags']
								))));
						}
						// Else drop from search
						else {
							clearFusionCMS::getEventManager()->notify(new flEvent('system.searchDeindex', array(
								'path' => array('testimonials', $params['id'])
							)));

							// Clear cached images
							$cfg = clearFusionCMS::getSiteConfig('cfSystemFileStore');
							$idHash = md5($params['id']);
							$path = $cfg->privateStorage . '/testimonials/' . clearFusionCMS::getSite() . '/' . $idHash[0] . '/' . $idHash[1] . '/' . $idHash;
							foreach(glob($path . '_*.*') as $f)
								@unlink($f);
						}

						$this->cache->flush();

						$this->session->flashSet('cfManagerOpSuccess', $this->alertMessage('Success', __('The testimonial has been updated.', 'testimonialsBackend')));
						$this->response->redirectTo($this->assemble('testimonials', 'edit', array($params['id']), true));
					}
					else
						$msg = $this->alertMessage('Error', __('Unable to update the testimonial, please try again.', 'testimonialsBackend'));
				}

				$content = $this->renderBlock(__('Edit Testimonial', 'testimonialsBackend'), $form->render($this->tpl->getCodeBuffer()), '', $msg);
			}

			$this->renderAdminPage($content);
		}
		else
			$this->response->redirectTo($this->assemble('testimonials', 'dashboard', array(), true));
	}

	/**
	 * Action for deleting a testimonial.
	 */
	function deleteAction() {
		$this->testPermission('cfTestimonials.post');
		$this->breadcrumbTrail->addCrumb(__('Testimonials', 'testimonialsBackend'), $this->assemble('testimonials', 'dashboard'));
		$this->breadcrumbTrail->addCrumb(__('Delete Testimonial', 'testimonialsBackend'), $this->assemble('testimonials', 'delete'));

		$route = new flRouterRoute(':id', array(), array('id' => '\d+'));
		if($params = $route->match($this->request->getParam('*', array()))) {

			if(($content = $this->lockObject('testimonials', $params['id'])) === true && ($data = $this->db->fetchRow('SELECT * FROM cf_testimonials_' . clearFusionCMS::getSite() . ' WHERE id=?', $params['id']))) {
				$form = new flForm($this->request, 'deleteform', $this->assemble('testimonials', 'delete', array($params['id'])), true);

				$name = new flFormElementText($form, 'name', $data['author']);
				$name->setLabel(__('Delete Testimonial', 'testimonialsBackend'))
					->setDisabled()
					->setReadonly();

				$delSubmit = new flFormElementSubmit($form, 'deletesubmit');
				$delSubmit->setCaption(__('Permanently Delete The Testimonial', 'testimonialsBackend'))
					->setCSS('danger')
					->setDescription($this->alertMessage('Warning', __('This operation cannot be undone and will delete the testimonial permanently.', 'testimonialsBackend')));

				$msg = '';
				if($form->isSubmitted() && $form->isValid()) {
					testimonialsAudit::delete($params['id'], $data);

					$this->db->delete('cf_testimonials_' . clearFusionCMS::getSite(), 'id=?', $params['id']);
					clearFusionCMS::getEventManager()->notify(new flEvent('system.searchDelete', array(
						'path' => array('testimonials', $params['id'])
					)));

					// Delete the thumb if there is one
					$this->getFilename($params['id']);

					$this->cache->flush();
					$this->response->redirectTo($this->assemble('testimonials', 'dashboard', array(), true));
				}

				$content = $this->renderBlock(__('Delete Testimonial', 'testimonialsBackend'), $form->render($this->tpl->getCodeBuffer()), '', $msg);
			}

			$this->renderAdminPage($content);
		}
		else
			$this->response->redirectTo($this->assemble('testimonials', 'dashboard', array(), true));
	}

	/**
	 * Get the filename to store a stories image under.
	 *
	 * Folders are created if required and old images are removed.
	 *
	 * @param int $id The ID of the story.
	 * @return bool|string The filename to use or false if failed.
	 */
	static function getFilename($id) {
		// Calculate the storage path and file name
		$cfg = clearFusionCMS::getSiteConfig('cfSystemFileStore');
		$idHash = md5($id);
		$path = $cfg->privateStorage . '/testimonials/' . clearFusionCMS::getSite() . '/' . $idHash[0] . '/' . $idHash[1] . '/';
		$file = $path . $idHash;

		// Create the folder if not already present
		if(!is_writable($path)) {
			if(!@mkdir($path, 0777, true))
				return false;
		}

		// Remove the old file if any
		foreach(glob($file . '.*') as $f)
			@unlink($f);

		foreach(glob($file . '_*.*') as $f)
			@unlink($f);

		return $file;
	}
}
