<?php
require_once(dirname(__FILE__).'/../../upgrade.php');
class move_attachments_from_db_to_file extends UPGRADE
{
	/**
	* IsAlreadyUpgraded
	* Do we need to run this classes upgrade script or not ?
	*
	* @return bool true if the upgrade has already run, otherwise false
	*/
	function IsAlreadyUpgraded()
	{
		$attachmentDirectory = realpath(dirname(__FILE__).'/../../../').'/attachments';

		return is_dir($attachmentDirectory);
	}

	/**
	* Upgrade
	* Do the actual upgrade of this component. If this is successful all
	* subsequent calls to IsAlreadyUpgraded should return true
	*
	* @return void
	*/
	function Upgrade()
	{
		$attachmentDirectory = realpath(dirname(__FILE__).'/../../../').'/attachments';

		mkdir($attachmentDirectory);
		chmod($attachmentDirectory, 0777);

		if (is_dir($attachmentDirectory)) {
			// Load all the attachments from the database
			$query = 'SELECT * FROM '.$GLOBALS['tablePrefix'].'attachments';
			$result = $GLOBALS['AKB_DB']->Query($query);

			while ($row = $GLOBALS['AKB_DB']->Fetch($result)) {
				error_log("Creating attachment dir for question id ".$row['aQuestId'].' '.$row['aFileName']);
				// Create the directory to save the file to
				mkdir($attachmentDirectory.DIRECTORY_SEPARATOR.$row['aQuestId']);
				chmod($attachmentDirectory.DIRECTORY_SEPARATOR.$row['aQuestId'], 0777);

				if (is_dir($attachmentDirectory.DIRECTORY_SEPARATOR.$row['aQuestId'])) {
					// Create the file
					$file = $attachmentDirectory.DIRECTORY_SEPARATOR.$row['aQuestId'].DIRECTORY_SEPARATOR.$row['aFileName'];
					$fp = fopen($file, 'wb');
					if ($fp) {
						fwrite($fp, $row['aData'], strlen($row['aData']));
						fclose($fp);
					}
					chmod($file, 0666);
				}
			}
		}
	}

}
?>
