<?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 - 2016 clearFusionCMS. All rights reserved.
 * @link http://clearfusioncms.com
 */

/**
 * testimonialsInstall Class
 *
 * Class for managing the testimonials module installation.
 *
 * @package clearFusionCMS\module\testimonials
 */
class testimonialsInstall implements cfInstallInterface {
	/**
	 * The last error message.
	 *
	 * @var string
	 */
	protected $lastError = '';

	/**
	 * Return the last error.
	 *
	 * @return string The last error string.
	 */
	function getLastError() {
		return $this->lastError;
	}

	/**
	 * Create the tables for the site.
	 *
	 * @param flDb $db The database object.
	 * @param string $site The site name.
	 */
	function createTables($db, $site) {
		// Create the database tables
		$db->query("CREATE  TABLE IF NOT EXISTS `cf_testimonials_{$site}` (
  `id` INT UNSIGNED NOT NULL AUTO_INCREMENT ,
  `dateoftestimonial` DATETIME NOT NULL ,
  `gender` CHAR NOT NULL ,
  `age` TINYINT NOT NULL ,
  `published` TINYINT NOT NULL ,
  `fileext` VARCHAR(4) NOT NULL ,
  `tags` VARCHAR(255) NOT NULL ,
  `author` VARCHAR(255) NOT NULL ,
  `location` VARCHAR(255) NOT NULL ,
  `email` VARCHAR(255) NOT NULL ,
  `occupation` VARCHAR(255) NOT NULL ,
  `website` VARCHAR(255) NOT NULL ,
  `company` VARCHAR(255) NOT NULL ,
  `testimonial` MEDIUMTEXT NOT NULL ,
  PRIMARY KEY (`id`) ,
  INDEX `dateoftestimonial` (`dateoftestimonial` DESC) ,
  INDEX `published` (`published` ASC ) )
ENGINE = MyISAM
DEFAULT CHARACTER SET = utf8
COLLATE = utf8_general_ci
");
	}

	/**
	 * Delete the tables.
	 *
	 * @param flDb $db The database object.
	 * @param string $site The name of the site to delete the table.
	 */
	function deleteTables($db, $site) {
		$db->query("DROP TABLE IF EXISTS cf_testimonials_{$site}");
	}

	/**
	 * Install the module.
	 *
	 * @param flDb The database object to use.
	 * @return bool true if installed; else false.
	 */
	function install($db) {
		// Test licence
		$cfInfo = new flModuleMgr($db);
		$info = $cfInfo->getInfo('testimonials');
		$sysLicence = new flConfigDb('cfSystemLicence', $db);
		$secret = 'RLV4T9U6AJ4CW8COK80400G8W8W4O0CH';
		$payload = array(
			'domain' => clearFusionCMS::getRequest()->getServerName(),
			'key' => $sysLicence->code,
			'subject' => 'testimonials',
			'version' => $info->version
		);
		$payload['hash'] = md5($secret . $payload['domain'] . $payload['key'] . $payload['subject'] . $payload['version']);

		$client = new flHttpClient('http://clearfusioncms.com/licence-remote-endpoint.json');
		$client->setPostData($payload);
		if($client->sendRequest() && $client->getResponseCode() == 200) {
			$res = json_decode($client->getBody());
			if($res->result != 'ok' && getenv('CLEARFUSIONCMS_ENV') !== 'development') {
				$this->lastError = $res->message;
				return false;
			}
		}
		else {
			$this->lastError = 'Unable to contact license server, please try again.';
			return false;
		}

		// Add to all sites
		$siteMgr = new cfSiteManager($db);
		$sites = $siteMgr->listSites();
		foreach($sites as $site => $n) {
			$this->createTables($db, $site);
			$cfg = $siteMgr->getSiteCfg('cfTestimonials', $site);
			$cfg->tw = '64';
			$cfg->th = '64';
			$cfg->tcrop = '1';
			$cfg->sw = '150';
			$cfg->sh = '150';
			$cfg->scrop = '1';
			$cfg->mw = '320';
			$cfg->mh = '320';
			$cfg->mcrop = '1';
			$cfg->lw = '640';
			$cfg->lh = '480';
			$cfg->lcrop = '0';
			$cfg->notifyEmail = '';
		}

		// Create permissions
		$ac = new flAcMgr($db);
		$ac->createPermissionGroup('cfTestimonials', __noop('Testimonials'), 'testimonialsBackend'); // 5100
		$ac->createPermission('cfTestimonials.post', __noop('Can post and manage testimonials.'), 5100, 'testimonialsBackend');
		$ac->createPermission('cfTestimonials.settings', __noop('Can edit testimonial settings.'), 5110, 'testimonialsBackend');

		// Add to dashboard
		$dmgr = new cfDashboardMgr($db);
		$dmgr->addIcon('cfContent', 'cfTestimonials', 'cfTestimonials.post', __noop('Testimonials'), __noop('Manage testimonials.'), 'system/modules/testimonials/images/testimonials.svg', 'testimonials', 'dashboard', 'testimonialsBackend');

		// Strings for translation
		__noop('Testimonial authors name');
		__noop('Testimonial body');
		__noop('Testimonial tags');

		return true;
	}

	/**
	 * Uninstall the module.
	 *
	 * @param flDb The database object to use.
	 * @return bool true if uninstalled; else false.
	 */
	function uninstall($db) {

		// Remove from dashboard
		$dmgr = new cfDashboardMgr($db);
		$dmgr->delIcon('cfTestimonials');

		// Remove permissions
		$ac = new flAcMgr($db);
		$ac->deletePermissionGroup('cfTestimonials');

		// Delete the news tables
		$siteMgr = new cfSiteManager($db);
		$sites = $siteMgr->listSites();
		foreach($sites as $site => $n) {
			$this->deleteSite($db, $site);
		}

		$cfg = clearFusionCMS::getSiteConfig('cfSystemFileStore');
		@rmdir($cfg->privateStorage . '/testimonials/');

		// Tell everyone this module has been removed
		clearFusionCMS::getEventManager()->notify(new flEvent('system.moduleRemoved', array(
			'module' => 'testimonials'
			)));

		return true;
	}

	/**
	 * Upgrade the module.
	 *
	 * @param flDb The database object to use.
	 * @param string $installedVer The installed version.
	 * @return bool true if upgraded; else false.
	 */
	function upgrade($db, $installedVer) {
		// Test licence
		$cfInfo = new flModuleMgr($db);
		$info = $cfInfo->getInfo('testimonials');
		$sysLicence = new flConfigDb('cfSystemLicence', $db);
		$secret = 'RLV4T9U6AJ4CW8COK80400G8W8W4O0CH';
		$payload = array(
			'domain' => clearFusionCMS::getRequest()->getServerName(),
			'key' => $sysLicence->code,
			'subject' => 'testimonials',
			'version' => $info->version
		);
		$payload['hash'] = md5($secret . $payload['domain'] . $payload['key'] . $payload['subject'] . $payload['version']);

		$client = new flHttpClient('http://clearfusioncms.com/licence-remote-endpoint.json');
		$client->setPostData($payload);
		if($client->sendRequest() && $client->getResponseCode() == 200) {
			$res = json_decode($client->getBody());
			if($res->result != 'ok' && getenv('CLEARFUSIONCMS_ENV') !== 'development') {
				$this->lastError = $res->message;
				return false;
			}
		}
		else {
			$this->lastError = 'Unable to contact license server, please try again.';
			return false;
		}

		if(version_compare($installedVer, '1.1.0') < 0) {
			// Create permissions
			$ac = new flAcMgr($db);
			$ac->createPermission('cfTestimonials.settings', __noop('Can edit testimonial settings.'), 5110, 'testimonialsBackend');
		}

		if(version_compare($installedVer, '1.2.0') < 0) {
			// Create permissions
			$ac = new flAcMgr($db);
			$ac->updatePermissionGroup('cfTestimonials', __noop('Testimonials'), 'testimonialsBackend');
			$ac->updatePermission('cfTestimonials.post', __noop('Can post and manage testimonials.'), 'testimonialsBackend');
			$ac->updatePermission('cfTestimonials.settings', __noop('Can edit testimonial settings.'), 'testimonialsBackend');

			// Add to dashboard
			$dmgr = new cfDashboardMgr($db);
			$dmgr->setIconName('cfTestimonials', __noop('Testimonials'), 'testimonialsBackend');
		}

		$siteMgr = new cfSiteManager($db);
		$sites = $siteMgr->listSites();
		if(version_compare($installedVer, '1.2.3') < 0) {
			foreach($sites as $site => $n)
				$db->query("ALTER TABLE cf_testimonials_{$site} ADD COLUMN company VARCHAR(255) NOT NULL AFTER website");
		}

		if(version_compare($installedVer, '1.3.2') < 0) {
			$dmgr = new cfDashboardMgr($db);
			$dmgr->setIconFile('cfTestimonials', 'system/modules/testimonials/images/testimonials.svg');
		}

		return true;
	}

	/**
	 * Create a new site.
	 *
	 * @param flDb $db The database object.
	 * @param string $site The short name of the site.
	 * @return bool true if the site was created; else false.
	 */
	function createSite($db, $site) {
		$this->createTables($db, $site);
		return true;
	}

	/**
	 * Delete a site.
	 *
	 * @param flDb $db The database object.
	 * @param string $site The name of the site to delete.
	 * @return bool true if the site was deleted; else false.
	 */
	function deleteSite($db, $site) {
		$this->deleteTables($db, $site);

		$siteMgr = new cfSiteManager($db);
		$cfg = $siteMgr->getSiteCfg('cfTestimonials', $site);
		$cfg->deleteNamespace();
		$cfg = $siteMgr->getSiteCfg('testimonialsSystemNotify', $site);
		$cfg->deleteNamespace();

		// Delete thumbnails for site
		$cfg = clearFusionCMS::getSiteConfig('cfSystemFileStore');
		$path = $cfg->privateStorage . '/testimonials/' . clearFusionCMS::getSite() . '/';

		$top = glob($path . '*', GLOB_NOSORT | GLOB_ONLYDIR);
		foreach($top as $td) {
			$second = glob("$td/*", GLOB_NOSORT | GLOB_ONLYDIR);
			foreach($second as $sd) {
				$files = glob("$sd/*.*", GLOB_NOSORT);
				foreach($files as $f) {
					@unlink($f);
				}
				@rmdir($sd);
			}
			@rmdir($td);
		}
		@rmdir($path);

		return true;
	}
}
