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

/**
 * contentInstall Class
 *
 * clearFusionCMS core module installer.
 *
 * @package clearFusionCMS\module\content
 */
class contentInstall 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;
	}

	/**
	 * Install the module.
	 *
	 * @param flDb The database object to use.
	 * @return bool true if installed; else false.
	 */
	function install($db) {
		return true;
	}

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

	/**
	 * 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) {
		// Only test licence if not encoded i.e. pro
		if(!function_exists('ioncube_file_is_encoded') || !ioncube_file_is_encoded()) {
			// Test licence
			$cfInfo = new flModuleMgr($db);
			$info = $cfInfo->getInfo('content');
			$sysLicence = new flConfigDb('cfSystemLicence', $db);
			$secret = 'RLV4T9U6AJ4CW8COK80400G8W8W4O0CH';
			$payload = array(
				'domain' => clearFusionCMS::getRequest()->getServerName(),
				'key' => isset($sysLicence->code) ? $sysLicence->code : '0000-0000-0000-0000-0000-0000-0000-0000',
				'subject' => function_exists('ioncube_file_is_encoded') && ioncube_file_is_encoded() ? 'clearFusionCMSFree' : 'clearFusionCMSPro',
				'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;
			}
		}

		// Force in for 1.3.0 and below or siteManager::listSites fails.
		$db->query('ALTER TABLE cf_sites ADD COLUMN locale VARCHAR(5) NOT NULL AFTER displayname');
		$db->query("ALTER TABLE cf_sites ADD COLUMN editperm VARCHAR(32) NOT NULL AFTER locale");

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

			// Modify site table to support aliases
			$db->query('ALTER TABLE cf_sites DROP PRIMARY KEY');
			$db->query('ALTER TABLE cf_sites ADD PRIMARY KEY(`shortname`, `domain`)');
			$db->query('ALTER TABLE cf_sites ADD INDEX `redirectto` (`redirectto` ASC)');

			// Delete redirect sites
			$aliases = array();
			$results = $db->query('SELECT shortname,domain,redirectto FROM cf_sites WHERE redirectto!=\'\'');
			while($row = $results->fetch()) {
				$siteMgr->deleteSite($row['shortname']);
				$aliases[$row['redirectto']][] = $row['domain'];
			}

			// Get sites
			$sites = array();
			$results = $db->query('SELECT shortname,domain FROM cf_sites');
			while($row = $results->fetch()) {
				if(isset($aliases["http://$row[domain]"])) {
					foreach($aliases["http://$row[domain]"] as $d) {
						$db->insert('cf_sites', array(
							'shortname' => $row['shortname'],
							'domain' => $d,
							'displayname' => '',
							'locale' => '',
							'editperm' => '',
							'redirectto' => "http://$row[domain]"
						));
					}
				}
			}

			// Move site selection to dashboard
			$dmgr = new cfDashboardMgr($db);
			$dmgr->addGroup('cfResources', 2000, __noop('Resources'));
			$dmgr->addIcon('cfSystem', 'cfSystem.selectsite', '', __noop('Select Site'), __noop('Select the site to work with.'), 'system/app/images/selectsite.svg', '', 'selectsite');
			$dmgr->setIconGroup('cfContent.elements', 'cfResources');
			$dmgr->setIconGroup('cfContent.filemgr', 'cfResources');
			$dmgr->setIconGroup('cfContent.privfilemgr', 'cfResources');
			$dmgr->setIconGroup('cfContent.settheme', 'cfResources');

			// Add new permissions
			$ac = new flAcMgr($db);
			$ac->updatePermission('core.settings',  __noop('Can access settings.'), 'cfBackend');
			$ac->createPermission('core.syssettings',  __noop('Can edit core system settings.'), 1045, 'cfBackend');
			$ac->createPermission('core.usersdel',  __noop('Can delete users.'), 1023, 'cfBackend');
			$ac->createPermission('core.usersadd',  __noop('Can add users.'), 1024, 'cfBackend');
			$ac->createPermission('core.usersroles',  __noop('Can assign users roles.'), 1027, 'cfBackend');
		}

		if(version_compare($installedVer, '1.2.0') < 0) {

			// Upgrade fusionLib database
			flDbInstaller::install($db);

			// Add meta_title
			$siteMgr = new cfSiteManager($db);
			$sites = $siteMgr->listSites();
			foreach($sites as $site => $n) {
				$db->query("ALTER TABLE cf_content_{$site} ADD COLUMN meta_title VARCHAR(255) NOT NULL AFTER subtitle");
			}

			// Add locale to sites
			$db->query("UPDATE cf_sites SET locale='en_US' WHERE redirectto=''");

			// Add text domain to dashboard groups and icons
			$db->query("ALTER TABLE cf_dashboardgrps ADD COLUMN textdomain VARCHAR(255) NOT NULL AFTER displayname");
			$db->query("ALTER TABLE cf_dashboardicons ADD COLUMN textdomain VARCHAR(255) NOT NULL AFTER description");

			// Add locks to system
			$db->query("CREATE  TABLE IF NOT EXISTS `cf_objlocks` (
  `modulename` VARCHAR(64) NOT NULL ,
  `contentid` VARCHAR(64) NOT NULL ,
  `sitename` VARCHAR(32) NOT NULL ,
  `uid` INT UNSIGNED NOT NULL ,
  `lockedat` DATETIME NOT NULL ,
  `hash` VARCHAR(32) NOT NULL ,
  PRIMARY KEY (`modulename`, `contentid`, `sitename`) ,
  INDEX `hash` (`hash` ASC) ,
  INDEX `uid` (`uid` ASC) ,
  INDEX `lockedat` (`lockedat` ASC) )
ENGINE = MyISAM
DEFAULT CHARACTER SET = utf8
COLLATE = utf8_general_ci
");

			// Add new permissions
			$ac = new flAcMgr($db);
			$ac->createPermission('cfContent.forceunlock', __noop('Can forcibly unlock items locked by other users.'), 2170, 'cfBackend');

			// Set text domain for existing permission groups and permissions
			$ac->updatePermissionGroup('core', __noop('System'), 'cfBackend');
			$ac->updatePermission('core.accessmgr', __noop('Can access the manager interface.'), 'cfBackend');
			$ac->updatePermission('core.users', __noop('Can manage users.'), 'cfBackend');
			$ac->updatePermission('core.usersdel', __noop('Can delete users.'), 'cfBackend');
			$ac->updatePermission('core.usersadd', __noop('Can add users.'), 'cfBackend');
			$ac->updatePermission('core.usersroles', __noop('Can assign users roles.'), 'cfBackend');
			$ac->updatePermission('core.roles', __noop('Can manage roles and permissions.'), 'cfBackend');
			$ac->updatePermission('core.settings', __noop('Can access settings.'), 'cfBackend');
			$ac->updatePermission('core.syssettings', __noop('Can edit core system settings.'), 'cfBackend');
			$ac->updatePermission('core.modules', __noop('Can install and uninstall modules.'), 'cfBackend');
			$ac->updatePermission('core.clearcache', __noop('Can manually clear the site data cache.'), 'cfBackend');
			$ac->updatePermission('core.fingerprint', __noop('Can create and test system fingerprints.'), 'cfBackend');

			$ac->updatePermissionGroup('cfContent', __noop('Content Editing'), 'cfBackend');
			$ac->updatePermission('cfContent.documents', __noop('Can edit documents.'), 'cfBackend');
			$ac->updatePermission('cfContent.canpublish', __noop('Can publish content.'), 'cfBackend');
			$ac->updatePermission('cfContent.candelete', __noop('Can delete content.'), 'cfBackend');
			$ac->updatePermission('cfContent.private', __noop('Can access and edit private files.'), 'cfBackend');
			$ac->updatePermission('cfContent.elements', __noop('Can manage content elements.'), 'cfBackend');
			$ac->updatePermission('cfContent.elemchunk', __noop('Can manage chunks.'), 'cfBackend');
			$ac->updatePermission('cfContent.elemfields', __noop('Can manage custom fields.'), 'cfBackend');
			$ac->updatePermission('cfContent.elemsnippet', __noop('Can manage snippets.'), 'cfBackend');
			$ac->updatePermission('cfContent.elemtemplate', __noop('Can manage templates.'), 'cfBackend');
			$ac->updatePermission('cfContent.elemtheme', __noop('Can manage themes.'), 'cfBackend');
			$ac->updatePermission('cfContent.settheme', __noop('Can set the active theme.'), 'cfBackend');
			$ac->updatePermission('cfContent.setdefpages', __noop('Can set the default page and error pages.'), 'cfBackend');
			$ac->updatePermission('cfContent.permissions', __noop('Can define content permissions.'), 'cfBackend');
			$ac->updatePermission('cfContent.types', __noop('Can create and manage content types.'), 'cfBackend');
			$ac->updatePermission('cfContent.managesites', __noop('Can manage the available sites within the system.'), 'cfBackend');
			$ac->updatePermission('cfContent.elemtasks', __noop('Can manage tasks.'), 'cfBackend');
			$ac->updatePermission('cfContent.forceunlock', __noop('Can forcibly unlock items locked by other users.'), 'cfBackend');

			// Set text domain for icons and icon groups
			$dmgr = new cfDashboardMgr($db);
			$dmgr->setGroupName('cfContent', __noop('Content'), 'cfBackend');
			$dmgr->setGroupName('cfResources', __noop('Resources'), 'cfBackend');
			$dmgr->setGroupName('cfSecurity', __noop('Security'), 'cfBackend');
			$dmgr->setGroupName('cfSystem', __noop('System'), 'cfBackend');

			$dmgr->setIconName('cfContent.documents', __noop('Documents'), 'cfBackend');
			$dmgr->setIconName('cfContent.elements',  __noop('Elements'), 'cfBackend');
			$dmgr->setIconName('cfContent.filemgr',  __noop('File Manager'), 'cfBackend');
			$dmgr->setIconName('cfContent.privfilemgr',  __noop('Private Files'), 'cfBackend');
			$dmgr->setIconName('cfContent.settheme', __noop('Set Theme'), 'cfBackend');
			$dmgr->setIconName('cfContent.drafts', __noop('Draft Docs'), 'cfBackend');
			$dmgr->setIconName('cfSecurity.contentperms', __noop('Content Perms'), 'cfBackend');
			$dmgr->setIconName('cfSecurity.roles', __noop('Roles'), 'cfBackend');
			$dmgr->setIconName('cfSecurity.users',  __noop('Users'), 'cfBackend');
			$dmgr->setIconName('cfSecurity.fingerprint', __noop('Fingerprint'), 'cfBackend');
			$dmgr->setIconName('cfSystem.clearcache', __noop('Clear Cache'), 'cfBackend');
			$dmgr->setIconName('cfSystem.contenttypes', __noop('Content Types'), 'cfBackend');
			$dmgr->setIconName('cfSystem.modules', __noop('Modules'), 'cfBackend');
			$dmgr->setIconName('cfSystem.set403', __noop('Set 403 Page'), 'cfBackend');
			$dmgr->setIconName('cfSystem.set404', __noop('Set 404 Page'), 'cfBackend');
			$dmgr->setIconName('cfSystem.setdefault', __noop('Set Home Page'), 'cfBackend');
			$dmgr->setIconName('cfSystem.settings', __noop('Settings'), 'cfBackend');
			$dmgr->setIconName('cfSystem.managesites', __noop('Manage Sites'), 'cfBackend');
			$dmgr->setIconName('cfSystem.selectsite', __noop('Select Site'), 'cfBackend');
		}

		if(version_compare($installedVer, '1.3.0') < 0) {
			// Upgrade fusionLib database
			flDbInstaller::install($db);

			$ac = new flAcMgr($db);
			$ac->createPermission('core.apikeys', __noop('Can create and manage API keys.'), 1080, 'cfBackend');
			$ac->createPermission('cfContent.selsites', __noop('Can select site to manage.'), 2155, 'cfBackend');

			$dmgr = new cfDashboardMgr($db);
			$dmgr->setGroupName('cfResources', __noop('Site'), 'cfBackend');
			$dmgr->addIcon('cfSystem', 'cfSystem.apikeys', 'core.apikeys', __noop('API Keys'), __noop('Manage API Keys.'), 'system/app/images/apikeys.svg', '', 'apikeys', 'cfBackend');
			$dmgr->delIcon('cfSystem.selectsite');
			$dmgr->addIcon('cfResources', 'cfSystem.selectsite', 'cfContent.selsites', __noop('Select Site'), __noop('Select the site to work with.'), 'system/app/images/selectsite.svg', '', 'selectsite', 'cfBackend');
			$dmgr->addIcon('cfSystem', 'cfSystem.seterror', 'cfContent.setdefpages', __noop('Set Error Page'), __noop('Set the page shown on errors other than 404 or 403.'), 'system/app/images/seterrorpage.svg', '', 'seterror', 'cfBackend');
			$dmgr->setIconGroup('cfSystem.clearcache', 'cfResources');
			$dmgr->setIconGroup('cfContent.filemgr', 'cfContent');
			$dmgr->setIconGroup('cfContent.privfilemgr', 'cfContent');
		}

		if(version_compare($installedVer, '1.4.0') < 0) {
			flDbInstaller::install($db);
			$dmgr = new cfDashboardMgr($db);
			$dmgr->setIconName('cfContent.drafts', __noop('Drafts'), 'cfBackend');
			$dmgr->setIconDesc('cfContent.drafts', __noop('View draft content.'), 'cfBackend');

			$siteMgr = new cfSiteManager($db);
			$sites = $siteMgr->listSites();
			foreach($sites as $site => $n) {
				$db->query("ALTER TABLE cf_content_{$site} ADD lftrgtset LINESTRING NOT NULL AFTER rgt");
				$db->query("UPDATE cf_content_{$site} SET lftrgtset=LineString(Point(-1,lft), Point(1, rgt))");
				$db->query("CREATE SPATIAL INDEX lftrgtset ON cf_content_{$site} (lftrgtset)");
			}
		}

		if(version_compare($installedVer, '2.0.0') < 0) {
			$ac = new flAcMgr($db);
			$ac->createPermission('cfContent.editpubdate', __noop('Can edit document publish dates.'), 2180, 'cfBackend');
			$db->query("ALTER TABLE cf_contenttype ADD snippet VARCHAR(64) NOT NULL AFTER fileext");
			$db->insert('cf_contenttype', array('gzip' => '1', 'typename' => '.less', 'mimetype' => 'text/css', 'fileext' => 'css', 'snippet' => 'lessc'));
			$db->query("ALTER TABLE cf_objlocks ADD `lockid` BIGINT UNSIGNED NOT NULL AFTER `hash`");

			$siteMgr = new cfSiteManager($db);
			$sites = $siteMgr->listSites();
			foreach($sites as $site => $n) {
				$db->query("ALTER TABLE cf_content_{$site} CHANGE restype restype ENUM('doc','link','static','folder') NOT NULL");
				$db->query("ALTER TABLE cf_content_{$site} ADD COLUMN cachetime INT NOT NULL AFTER contenttype");

				$cfg = $siteMgr->getSiteCfg('cfSystemNotify', $site);
				$cfg->deleteNamespace();
			}

			$db->query("ALTER TABLE cf_dashboardgrps ADD faicon VARCHAR(32) NOT NULL AFTER textdomain");

			$dmgr = new cfDashboardMgr($db);
			$dmgr->setGroupFAIcon('cfContent', 'fa-file-o');
			$dmgr->setGroupFAIcon('cfResources', 'fa-code');
			$dmgr->setGroupFAIcon('cfSecurity', 'fa-lock');
			$dmgr->setGroupFAIcon('cfSystem', 'fa-cog');
		}

		if(version_compare($installedVer, '2.0.1') < 0) {
			// Upgrade fusionLib database
			flDbInstaller::install($db);
		}

		if(version_compare($installedVer, '2.1.0') < 0) {
			// Upgrade fusionLib database
			flDbInstaller::install($db);

			$ac = new flAcMgr($db);
			$ac->createPermissionGroup('cfSocialImg', __noop('Social Media Images'), 'cfBackend'); // 3000
			$ac->createPermission('cfSocialImg.canedit', __noop('Can edit images used in social networks.'), 3000, 'cfBackend');
			$ac->createPermission('cfSocialImg.candelete', __noop('Can delete images used in social networks.'), 3010, 'cfBackend');
			$ac->createPermission('cfSocialImg.canadd', __noop('Can add images used in social networks.'), 3020, 'cfBackend');

			$dmgr = new cfDashboardMgr($db);
			$dmgr->addIcon('cfResources', 'cfSystem.socialimg', 'cfSocialImg.canedit', __noop('Social Images'), __noop('Manage Social Media Images.'), 'system/app/images/social_images.svg', '', 'socialimgs', 'cfBackend');

			$db->query("ALTER TABLE cf_sites ADD `twitterusername` VARCHAR(255) NOT NULL AFTER redirectto");
			$db->query("ALTER TABLE cf_dashboardgrps ADD   `mdicon` VARCHAR(64) NOT NULL AFTER faicon");

			$siteMgr = new cfSiteManager($db);
			$sites = $siteMgr->listSites();
			foreach($sites as $site => $n) {
				$db->query("ALTER TABLE cf_content_{$site} ADD `ogtitle` VARCHAR(255) NOT NULL AFTER menutitle");
				$db->query("ALTER TABLE cf_content_{$site} ADD `ogdesc` VARCHAR(255) NOT NULL AFTER ogtitle");
				$db->query("ALTER TABLE cf_content_{$site} ADD `twittertitle` VARCHAR(255) NOT NULL AFTER ogdesc");
				$db->query("ALTER TABLE cf_content_{$site} ADD `twitterdesc` VARCHAR(255) NOT NULL AFTER twittertitle");

				$db->query("ALTER TABLE cf_content_{$site} ADD `ogimageid` INT UNSIGNED NOT NULL AFTER cachetime");
				$db->query("ALTER TABLE cf_content_{$site} ADD `twitterimageid` INT UNSIGNED NOT NULL AFTER ogimageid");

				$db->query("CREATE TABLE IF NOT EXISTS `cf_socialimages_{$site}` (
  `imageid` INT UNSIGNED NOT NULL AUTO_INCREMENT,
  `ext` VARCHAR(4) NOT NULL ,
  `title` VARCHAR(255) NOT NULL ,
  INDEX `uid` (`imageid` ASC) )
ENGINE = MyISAM
DEFAULT CHARACTER SET = utf8
COLLATE = utf8_general_ci
");

				$db->query("ALTER TABLE cf_search_{$site}_docs MODIFY publishedat DATETIME NULL");
				$db->query("UPDATE cf_search_{$site}_docs SET publishedat=NULL WHERE publishedat='0000-00-00 00:00:00'");

				$db->query("ALTER TABLE cf_content_{$site} MODIFY publishedat DATETIME NULL");
				$db->query("UPDATE cf_content_{$site} SET publishedat=NULL WHERE publishedat='0000-00-00 00:00:00'");

				$db->query("ALTER TABLE cf_sites MODIFY twitterusername VARCHAR(32) DEFAULT ''");
			}

			$dmgr->setGroupMDIcon('cfContent', 'description');
			$dmgr->setGroupMDIcon('cfResources', 'code');
			$dmgr->setGroupMDIcon('cfSecurity', 'security');
			$dmgr->setGroupMDIcon('cfSystem', 'settings');
			$dmgr->setIconGroup('cfSystem.socialimg', 'cfContent');

			$dmgr->setIconFile('cfSystem.apikeys', 'system/app/images/apikeys.svg');
			$dmgr->setIconFile('cfSystem.clearcache', 'system/app/images/clearcache.svg');
			$dmgr->setIconFile('cfContent.documents', 'system/app/images/content.svg');
			$dmgr->setIconFile('cfContent.drafts', 'system/app/images/content_drafts.svg');
			$dmgr->setIconFile('cfContent.elements', 'system/app/images/elements.svg');
			$dmgr->setIconFile('cfContent.filemgr', 'system/app/images/filemgr.svg');
			$dmgr->setIconFile('cfContent.privfilemgr', 'system/app/images/privfilemgr.svg');
			$dmgr->setIconFile('cfSecurity.fingerprint', 'system/app/images/fingerprint.svg');
			$dmgr->setIconFile('cfSystem.modules', 'system/app/images/modules.svg');
			$dmgr->setIconFile('cfSecurity.roles', 'system/app/images/roles.svg');
			$dmgr->setIconFile('cfSecurity.users', 'system/app/images/users.svg');
			$dmgr->setIconFile('cfSystem.selectsite', 'system/app/images/selectsite.svg');
			$dmgr->setIconFile('cfSystem.set403', 'system/app/images/403page.svg');
			$dmgr->setIconFile('cfSystem.set404', 'system/app/images/link_broken.svg');
			$dmgr->setIconFile('cfSystem.seterror', 'system/app/images/seterrorpage.svg');
			$dmgr->setIconFile('cfSystem.setdefault', 'system/app/images/sethome.svg');
			$dmgr->setIconFile('cfContent.settheme', 'system/app/images/settheme.svg');
			$dmgr->setIconFile('cfSystem.settings', 'system/app/images/settings.svg');
			$dmgr->setIconFile('cfSystem.managesites', 'system/app/images/sitemgr.svg');
			$dmgr->setIconFile('cfSecurity.contentperms', 'system/app/images/ctntperms.svg');
			$dmgr->setIconFile('cfSystem.contenttypes', 'system/app/images/ctnttypes.svg');

		}

		if(version_compare($installedVer, '3.0.1') < 0) {
			// Upgrade fusionLib database
			flDbInstaller::install($db);

			$siteMgr = new cfSiteManager($db);
			$sites = $siteMgr->listSites();
			foreach ($sites as $site => $n) {
				$db->query("ALTER TABLE `cf_search_{$site}_fields` ADD COLUMN `fldtype` ENUM('text','int','number') DEFAULT 'text'  NOT NULL AFTER `fldid`");

				$db->query("
CREATE  TABLE IF NOT EXISTS cf_search_{$site}_ints (
  `fldid` TINYINT UNSIGNED NOT NULL ,
  `id` INT UNSIGNED NOT NULL ,
  `val` INT NOT NULL ,
  PRIMARY KEY (`fldid`, `id`) ,
  INDEX `docid` (`id` ASC) ,
  INDEX `val` (`val` ASC) )
ENGINE = MyISAM
DEFAULT CHARACTER SET = utf8
COLLATE = utf8_general_ci
");

				$db->query("
CREATE  TABLE IF NOT EXISTS cf_search_{$site}_nums (
  `fldid` TINYINT UNSIGNED NOT NULL ,
  `id` INT UNSIGNED NOT NULL ,
  `val` DECIMAL(13, 4) NOT NULL ,
  PRIMARY KEY (`fldid`, `id`) ,
  INDEX `docid` (`id` ASC) ,
  INDEX `val` (`val` ASC) )
ENGINE = MyISAM
DEFAULT CHARACTER SET = utf8
COLLATE = utf8_general_ci
");
			}
		}

		if(version_compare($installedVer, '3.0.2') < 0) {
			$db->insert('cf_contenttype', array('gzip' => '1', 'typename' => '.md', 'mimetype' => 'text/markdown', 'fileext' => 'md', 'snippet' => ''));
		}

		if(version_compare($installedVer, '3.0.4') < 0) {
			$db->query("ALTER TABLE `cf_contenttype` ADD COLUMN `editor` VARCHAR(64) DEFAULT ''  NOT NULL AFTER `snippet`");
			$db->query("UPDATE `cf_contenttype` SET `editor`='codemirror' WHERE `typename` IN ('.php','.css','.js','.xml','.txt','.json','.less','.md')");

			$db->query("ALTER TABLE `cf_customflds` ADD COLUMN `editor` VARCHAR(64) DEFAULT ''  NOT NULL AFTER `editperm`");
			$db->query("ALTER TABLE `cf_customflds` ADD COLUMN `snippet` VARCHAR(64) DEFAULT ''  NOT NULL AFTER `editor`");

			$db->insert('cf_contenttype', array('gzip' => '1', 'typename' => 'Markdown', 'mimetype' => 'text/html', 'fileext' => '', 'snippet' => 'parseMarkdown'));

			// Copy twitter keys from social module if available
			$siteMgr = new cfSiteManager($db);
			$sites = $siteMgr->listSites();
			foreach ($sites as $site => $n) {
				$cfg = $siteMgr->getSiteCfg('cfSocial', $site);
				$consumer = $cfg->get('consumerKey');
				$secret = $cfg->get('consumerSecret');

				if($consumer && $secret) {
					$social = $siteMgr->getSiteCfg('cfSystemSocialAPI', $site);
					$social->twitter_consumer = str_rot13($consumer);
					$social->twitter_secret = str_rot13($secret);
				}
			}
		}

		if(version_compare($installedVer, '3.1.0') < 0) {
			// Upgrade fusionLib database
			flDbInstaller::install($db);

			$ac = new flAcMgr($db);
			$ac->createPermission('core.audit', __noop('Can view the audit log.'), 1090, 'cfBackend');
			$ac->createPermission('core.auditSettings', __noop('Can view settings data in audit log.'), 1100, 'cfBackend');

			$dmgr = new cfDashboardMgr($db);
			$dmgr->addIcon('cfSecurity', 'cfSecurity.audit', 'core.audit', __noop('Audit Log'), __noop('View the audit log.'), 'system/app/images/audit.svg', '', 'audit', 'cfBackend');

			$siteMgr = new cfSiteManager($db);
			$sites = $siteMgr->listSites();
			foreach ($sites as $site => $n) {
				$db->query("CREATE TABLE IF NOT EXISTS `cf_auditlog_{$site}` (
  `auditid` INT UNSIGNED NOT NULL AUTO_INCREMENT,
  `action` INT UNSIGNED NOT NULL ,
  `module` VARCHAR(64) NOT NULL ,
  `cid` INT UNSIGNED NOT NULL ,
  `uid` INT UNSIGNED NOT NULL ,
  `loggedat` DATETIME NOT NULL ,
  `ip` VARCHAR(64) NOT NULL ,
  `params` MEDIUMTEXT NOT NULL ,
  `previous` MEDIUMTEXT NOT NULL ,
  PRIMARY KEY (`auditid`) ,
  INDEX `uid` (`uid` ASC) ,
  INDEX `modulecid` (`module`, `cid` ASC) ,
  INDEX `loggedat` (`loggedat` ASC))
ENGINE = MyISAM
DEFAULT CHARACTER SET = utf8
COLLATE = utf8_general_ci
");

				$db->query("ALTER TABLE `cf_sites` ADD COLUMN `puressl` TINYINT NOT NULL DEFAULT '0' AFTER `twitterusername`");
			}

			$db->update('cf_contenttype', array('snippet' => 'packjs'), 'fileext=?', 'js');
		}

		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) {
		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) {
		return true;
	}
}
