<?php
/**
 * ###############################################
 *
 * SWIFT Framework
 * _______________________________________________
 *
 * @author         Varun Shoor
 *
 * @package        SWIFT
 * @copyright      Copyright (c) 2001-2012, Kayako
 * @license        http://www.kayako.com/license
 * @link           http://www.kayako.com
 *
 * ###############################################
 */

/**
 * The Main Installer
 *
 * @author Varun Shoor
 */
class SWIFT_SetupDatabase_core extends SWIFT_SetupDatabase
{
	// Core Constants
	const PAGE_COUNT = 1;

	/**
	 * Constructor
	 *
	 * @author Varun Shoor
	 * @return bool "true" on Success, "false" otherwise
	 */
	public function __construct()
	{
		parent::__construct(APP_CORE);

		return true;
	}

	/**
	 * Destructor
	 *
	 * @author Varun Shoor
	 * @return bool "true" on Success, "false" otherwise
	 */
	public function __destruct()
	{
		parent::__destruct();

		return true;
	}

	/**
	 * Loads the table into the container
	 *
	 * @author Varun Shoor
	 * @return bool "true" on Success, "false" otherwise
	 */
	public function LoadTables()
	{
		// ======= MAILQUEUEDATA =======
		$this->AddTable('mailqueuedata', new SWIFT_SetupDatabaseTable(TABLE_PREFIX . "mailqueuedata", "mailqueuedataid I PRIMARY AUTO NOTNULL,
																toemail C(255) DEFAULT '' NOTNULL,
																fromemail C(255) DEFAULT '' NOTNULL,
																fromname C(255) DEFAULT '' NOTNULL,
																subject C(255) DEFAULT '' NOTNULL,
																datatext XL,
																datahtml XL,
																dateline I DEFAULT '0' NOTNULL,
																ishtml I2 DEFAULT '0' NOTNULL"));

		// ======= FILES =======
		$this->AddTable('files', new SWIFT_SetupDatabaseTable(TABLE_PREFIX . "files", "fileid I PRIMARY AUTO NOTNULL,
																filename C(255) DEFAULT '' NOTNULL,
																originalfilename C(255) DEFAULT '' NOTNULL,
																filehash C(100) DEFAULT '' NOTNULL,
																dateline I DEFAULT '0' NOTNULL,
																expiry I DEFAULT '0' NOTNULL,
																subdirectory C(255) DEFAULT '' NOTNULL"));
		$this->AddIndex('files', new SWIFT_SetupDatabaseIndex("files1", TABLE_PREFIX . "files", "dateline, expiry"));
		$this->AddIndex('files', new SWIFT_SetupDatabaseIndex("files2", TABLE_PREFIX . "files", "expiry"));


		return true;
	}


	/**
	 * Get the Page Count for Execution
	 *
	 * @author Varun Shoor
	 * @return bool "true" on Success, "false" otherwise
	 */
	public function GetPageCount()
	{
		return self::PAGE_COUNT;
	}

	/**
	 * Function that does the heavy execution
	 *
	 * @author Varun Shoor
	 *
	 * @param int $_pageIndex The Page Index
	 *
	 * @return bool "true" on Success, "false" otherwise
	 */
	public function Install($_pageIndex)
	{
		if (strtolower(DB_TYPE) == 'mysql' || strtolower(DB_TYPE) == 'mysqli')
		{
			$this->Query(new SWIFT_SetupDatabaseSQL("ALTER DATABASE " . DB_NAME . " CHARACTER SET 'utf8' COLLATE 'utf8_unicode_ci'"));
		}

		parent::Install($_pageIndex);

		if (strtolower(DB_TYPE) == 'mysql' || strtolower(DB_TYPE) == 'mysqli')
		{
			$this->Query(new SWIFT_SetupDatabaseSQL("ALTER TABLE " . TABLE_PREFIX . "sessions TYPE = HEAP"));
		}

		$this->ExecuteQueue();

		if ($this->GetStatus() == true) {
			// ======= SETTINGS =======
			$this->Settings->InsertKey('core', 'version', SWIFT_VERSION);
			$this->Settings->InsertKey('core', 'product', SWIFT_PRODUCT);
			$this->Settings->InsertKey('core', 'installationhash', BuildHash());
			$this->Settings->InsertKey('cron', 'nextrun', time());

			// ======= REST API =======
			$_SWIFT_RESTManagerObject = new SWIFT_RESTManager();
			$_SWIFT_RESTManagerObject->ReGenerateAuthenticationData(false);

			// Create default cron tasks
			$this->SyncCronTasks();
		}

		return true;
	}

	/**
	 * Uninstalls the App
	 *
	 * @author Varun Shoor
	 * @return bool "true" on Success, "false" otherwise
	 */
	public function Uninstall()
	{
		parent::Uninstall();

		return true;
	}

	/**
	 * Syncrhonize the cron tasks
	 *
	 * @author Varun Shoor
	 * @return bool "true" on Success, "false" otherwise
	 * @throws SWIFT_Exception If the Class is not Loaded
	 */
	protected function SyncCronTasks()
	{
		if (!$this->GetIsClassLoaded()) {
			throw new SWIFT_Exception(__CLASS__ . ':  ' . SWIFT_CLASSNOTLOADED);
		}

		$_cronTaskList = array();
		$this->Database->Query("SELECT * FROM " . TABLE_PREFIX . "cron WHERE app = 'core'");
		while ($this->Database->NextRecord()) {
			$_cronTaskList[] = strtolower('/' . $this->Database->Record['app'] . '/' . $this->Database->Record['controller'] . '/' . $this->Database->Record['action']);
		}

		// Cron Minute
		if (!in_array('/core/minute/index', $_cronTaskList)) {
			SWIFT_Cron::Create('defaultcoreminute', 'Core', 'Minute', 'Index', '0', '3', '0', true);
		}

		// Cron Hourly
		if (!in_array('/core/hourly/index', $_cronTaskList)) {
			SWIFT_Cron::Create('defaultcorehourly', 'Core', 'Hourly', 'Index', '-1', '0', '0', true);
		}

		// Cron Daily
		if (!in_array('/core/daily/index', $_cronTaskList)) {
			SWIFT_Cron::Create('defaultcoredaily', 'Core', 'Daily', 'Index', '0', '0', '-1', true);
		}

		// Cron Weekly
		if (!in_array('/core/weekly/index', $_cronTaskList)) {
			SWIFT_Cron::Create('defaultcoreweekly', 'Core', 'Weekly', 'Index', '0', '0', '7', true);
		}

		// Cron Monthly
		if (!in_array('/core/monthly/index', $_cronTaskList)) {
			SWIFT_Cron::Create('defaultcoremonthly', 'Core', 'Monthly', 'Index', '0', '0', '30', true);
		}

		return true;
	}

	/**
	 * Upgrade the App
	 *
	 * @author Varun Shoor
	 *
	 * @param bool $_isForced
	 *
	 * @return bool "true" on Success, "false" otherwise
	 */
	public function Upgrade($_isForced = false)
	{
		return parent::Upgrade($_isForced);
	}

	/**
	 * Performs upgrade steps for 4.01.161
	 *
	 * - Removes tables from old search engine app
	 * - Removes old search engine cron task
	 *
	 * @author Ryan Lederman <rml@kayako.com>
	 * @return bool
	 */
	public function Upgrade_4_01_161()
	{
		if (!$this->GetIsClassLoaded()) {
			throw new SWIFT_Exception(SWIFT_CLASSNOTLOADED);

			return false;
		}

		// Drop tables we don't use anymore
		$this->Database->Query("DROP TABLE IF EXISTS " . TABLE_PREFIX . "searchtextngrams, " . TABLE_PREFIX . "searchtextinstances, " . TABLE_PREFIX . "searchtextvariables;");

		// Remove deprecated cron entry
		return $this->Database->Query("DELETE FROM " . TABLE_PREFIX . "cron WHERE name = 'cronsearchengine';");
	}

	/**
	 * Performs upgrade steps for 4.01.180
	 *
	 * - Forces searchindex table to use the MyISAM engine
	 *
	 * @author Ryan Lederman <rml@kayako.com>
	 * @return bool
	 */
	public function Upgrade_4_01_180()
	{
		if (!$this->GetIsClassLoaded()) {
			throw new SWIFT_Exception(SWIFT_CLASSNOTLOADED);

			return false;
		}

		return $this->Database->Query("ALTER TABLE " . TABLE_PREFIX . "searchindex ENGINE=MyISAM;");
	}

	/**
	 * Performs upgrade steps for 4.50.1636
	 *
	 * @author Parminder Singh
	 * @return bool
	 */
	public function Upgrade_4_50_1637()
	{
		if (!$this->GetIsClassLoaded()) {
			throw new SWIFT_Exception(SWIFT_CLASSNOTLOADED);
		}

		$this->SyncCronTasks();

		return true;
	}

	/**
	 * Upgrade for 4.60
	 * Remove section and setting
	 *
	 * @author Ashish Kataria
	 * @return bool "true" on Success, "false" otherwise
	 * @throws SWIFT_Exception If the Class is not Loaded
	 */
	public function Upgrade_4_60_0()
	{
		if (!$this->GetIsClassLoaded()) {
			throw new SWIFT_Exception(SWIFT_CLASSNOTLOADED);
		}

		/**
		 * BUG FIX - Amarjeet Kaur
		 *
		 * SWIFT-3318: Add an upgrade step to reset the customized logos to the new default logos
		 *
		 * Comments: none
		 */
		$_headerImages = $this->Database->QueryFetch("SELECT COUNT(*) AS totalHeaderImages FROM " . TABLE_PREFIX . "settings WHERE section = 'headerimage'");
		if ($_headerImages['totalHeaderImages'] > 0) {
			$this->Settings->DeleteSection('headerimage');
		}

		/**
		 * Improvement  - Ashish Kataria
		 *
		 * SWIFT-3328 Remove 'Display Top Logo Header' setting
		 *
		 * Comments: Delete Display top header settings
		 */
		$this->Settings->DeleteKey('settings', 'g_displaytopheader');

		return true;
	}

	/**
	 * Upgrade for 4.70
	 *
	 * @author Ravi Sharma <ravi.sharma@kayako.com>
	 * @throws SWIFT_Exception
	 * @return bool
	 */
	public function Upgrade_4_70_2223()
	{
		if (!$this->GetIsClassLoaded()) {
			throw new SWIFT_Exception(SWIFT_CLASSNOTLOADED);
		}

		// Updating onsite port
		$this->Database->Query("UPDATE " . TABLE_PREFIX . "settings SET data='2567' WHERE vkey='ons_xmppport_1'");

		return true;
	}

	/**
	 * Upgrade from 4.70.2
	 *
	 * @author Mansi Wason <mansi.wason@kayako.com>
	 *
	 * @return bool
	 * @throws SWIFT_Exception 
	 */
	public function Upgrade_4_71_0000()
	{
		if (!$this->GetIsClassLoaded()) {
			throw new SWIFT_Exception(SWIFT_CLASSNOTLOADED);

			return false;
		}

		// Remove deprecated onsite entry
		return $this->Database->Query("DELETE FROM " . TABLE_PREFIX . "settingsgroups WHERE name = 'settings_onsite';");
	}
}
