<?php
/**
 *This controller is responsible for processing actions with plugins
 *
 *@author Pavel Savchuk
 */
class Backend_PluginController extends RCMS_Core_BaseController {

	public  $pathPlugin;

	protected $_languageId;

	protected $_languageName;

	protected $_browsePlugins="";

	public function init() {
		parent::init();
		$this->_model = new Default_Model_PluginModel();

		$this->_languageId = $this->_session->langId;
/*		$this->_languageName = strtolower($this->_model->selectLanguageById($this->_languageId));
		if($this->_languageName=="")*/
		$this->_languageName = $this->_languageId;
		if($this->_languageName=="") {
			$this->_browsePlugins  = 'swf-browse-plugins.png';
		}else {
			$this->_browsePlugins = 'swf-browse-plugins'."-".$this->_languageName.".png";
			if(!file_exists('system/js/swfupload/'.$this->_browsePlugins)) {
				$this->_browsePlugins = 'swf-browse-plugins.png';
			}
		}

		$this->pathPlugin = $this->_config->website->website->path."public/plugins/";
		$this->_pathThemes = $this->_config->website->website->path . $this->_config->website->website->themesPath;
		$this->_currentThemeName = $this->_model->selectCurrentTheme();
	}

	/**
	 * This function loads template for upload a theme.
	 * @return void
	 */
	public function indexAction() {
		$this->checkLogin();
		$this->_helper->getHelper('layout')->disableLayout();
		$this->view->success = $this->getRequest()->getParam('success');
		$this->view->pathPlugin = $this->pathPlugin;
		$listPlugins = RCMS_Tools_FilesystemTools::scanDir($this->pathPlugin);

		$this->view->browsePlugins = $this->_browsePlugins;

		foreach ($listPlugins as &$plugin) {
			$result = $this->_model->selectPluginByName($plugin);


			if($result) {
				$plugin = array('name'=>$plugin ,'status'=>$result['status'],'cache'=>$result['cache'],'inDb'=>'1');
			}else {
				$plugin = array('name'=>$plugin ,'status'=>'disabled','cache'=>'0','inDb'=>'0');
			}
		}

		$this->view->websiteUrl = $this->getWebSiteUrl();
		$this->view->listPlugins = $listPlugins;
		$this->view->zipExtensionEnabled = (extension_loaded('zip')==true?true:false);
		$content = $this->_translator->processScreen($this->view->render($this->getViewScript()));
		$this->_helper->viewRenderer->setNoRender(true);
		echo $content;
	}


	/**
	 * This function loads template for upload a theme.
	 * @return void
	 */
	public function readmeAction() {
		$this->checkLogin();
		$this->_helper->getHelper('layout')->disableLayout();
		if($this->getRequest()->getParam('pluginName')) {
			$pluginName = strtolower($this->getRequest()->getParam('pluginName'));
			if(file_exists("../public/plugins/".$pluginName."/readme.txt")) {
				$readmeContent = addslashes(htmlspecialchars(file_get_contents("../public/plugins/".$pluginName."/readme.txt")));
				if(trim($readmeContent)=="") {
					$readmeContent="Readme.txt for this plugin is empty.";
				}
			}
		}
		$this->view->pluginName = $pluginName;
		$this->view->readmeContent = $readmeContent;
		$content = $this->_translator->processScreen($this->view->render($this->getViewScript()));
		$this->_helper->viewRenderer->setNoRender(true);
		echo $content;
	}

	/**
	 * This function uploads a plugin and saves it into the filesystem.
	 * @return void
	 */
	public function uploadpluginAction() {
		$this->_helper->getHelper('layout')->disableLayout();
		$this->_helper->viewRenderer->setNoRender(true);

		$file = new Zend_File_Transfer_Adapter_Http();
		$data = $file->getFileInfo();
		$tmpFolder = $this->_config->website->website->path . $this->_config->website->website->tmp;

		$zip = new ZipArchive();
		$zip->open($data['Filedata']['tmp_name']);
		$zip->extractTo($tmpFolder);

		$this->_overwriteTheme = $this->getRequest()->getParam('overwrite');
		$check = $this->_validatePlugin($tmpFolder);
		$this->_deletePluginFromTmpFolder($tmpFolder);

		if(!empty($check)) {
			$zip->close();
			echo json_encode(array('error'=>$check['error'], 'message'=>$check['message']));
			exit();
		}
		else {
			if($this->_overwriteTheme === 'true' && is_dir($this->pathPlugin . $this->_uploadPluginName)) {
				echo json_encode(array('error'=>false, 'exist_plugin'=>true));
				exit();
			}
			else {
				$zip->extractTo($this->pathPlugin);
				$zip->close();

				$previewPicture = '';
				$listFilesInTheme = RCMS_Tools_FilesystemTools::scanDir($this->pathPlugin . $this->_uploadPluginName);

				foreach ($listFilesInTheme as $file) {
					if(preg_match('/^preview\.(jpg|gif|png)$/', $file) && $previewPicture == '') {
						$previewPicture = $file;
						break;
					}
				}

				$path = $this->pathPlugin . $this->_uploadPluginName;
				RCMS_Tools_FilesystemTools::mkDir($path . '/images/templatepreview/');
				if(file_exists($path . '/' .$previewPicture)) {
					$srcPreviewPicture = $this->_config->website->website->url . 'plugins/' . $this->_uploadPluginName . '/' . $previewPicture;
				}
				else {
					$srcPreviewPicture = $this->_config->website->website->url . 'system/images/noimage.png';
				}

				echo json_encode(array('error'=>false, 'exist_plugin'=>false, 'plugin'=>$this->_uploadPluginName, 'preview'=>$srcPreviewPicture));
				exit();
			}
		}
	}

	/**
	 * This function checks name of theme and returns array of errors.
	 * @param type $folder
	 * @return array
	 */
	private function _validatePlugin($folder) {
		if(!is_dir($folder)) {
			return array('error'=>true, 'message'=>'Can not create folder for unpack zip file. 0peration not permitted.');
		}

		$namePlugin = RCMS_Tools_FilesystemTools::scanDir($folder);
     /*   if(count($nameTheme) > 1)
        {
            return array('error'=>true, 'message'=>'Your direrctory structure is invalid.');
        }
*/
		$namePlugin = strtolower($namePlugin[0]);
		$listFiles = RCMS_Tools_FilesystemTools::scanDir($folder . $namePlugin);
		if(empty($listFiles)) {
			return array('error'=>true, 'message'=>'Your plugin directory is empty.');
		}
/*
        if(!preg_match("/^[a-zA-Z-0-9]{1,255}$/", $namePlugin))
        {
            return array('error'=>true, 'message'=>'Plugin name is invalid. Only letters, digits and dashes allowed.');
        }*/

		if(!file_exists($folder . $namePlugin . '/system/install.sql')) {
			return array('error'=>true, 'message'=>'File "install.sql" doesn\'t exists.');
		}

		if(!file_exists($folder . $namePlugin . '/readme.txt')) {
			return array('error'=>true, 'message'=>'File "readme.txt" doesn\'t exists.');
		}

		if(!file_exists($folder . $namePlugin . '/system/uninstall.sql')) {
			return array('error'=>true, 'message'=>'File "uninstall.sql" doesn\'t exists.');
		}

		if( is_dir($this->pathPlugin. $namePlugin)) {
			return array('error'=>true, 'message'=>'Plugin with such a name already exists.');
		}

		$this->_uploadPluginName = $namePlugin;

		return array();
	}

	/**
	 * This function deletes a plugin from filesystem.
	 * @param string $path
	 * @return void
	 */
	private function _deletePluginFromTmpFolder($path) {
		if(is_dir($path)) {
			if($dir_handle = opendir($path)) {
				while(false !== ($file = readdir($dir_handle))) {
					if($file == '.' || $file == '..' || $file == '.svn') {
						continue;
					}
					if(is_dir($path . $file)) {
						$this->_deletePluginFromTmpFolder($path . $file . '/');
					}
					else {
						@unlink($path . $file);
					}
				}
				closedir($dir_handle);
				RCMS_Tools_FilesystemTools::rmDir($path);
			}
		}
	}

	public function disablepluginAction() {
		$this->_helper->getHelper('layout')->disableLayout();
		$this->_helper->viewRenderer->setNoRender(true);
		//$this->checkLogin();
		$success = null;
		$websiteUrl = $this->getWebSiteUrl();
		if($this->getRequest()->isPost() && $this->getRequest()->getParam('pluginName')) {
			$pluginName =  $this->getRequest()->getParam('pluginName');
			if($pluginName && $pluginName!="") {
				$result = $this->_model->selectPluginByName($pluginName);
				$pluginNameProcessed = str_replace(" ","-",$pluginName);
				if($result) {
					$pluginObj = new RCMS_Object_Plugin_Plugin($result['id']);
					$pluginObj->setStatus('disabled');
					$pluginObj->save();
				}

				echo '<p  id="pluginstatus-'.$pluginNameProcessed.'">
				<button class="formsubmit" style="font-weight:bold;width:100px;font-size:12px;" onclick="enablePlugin(\''.$websiteUrl.'\',\''.$pluginName.'\')">Enable</button>
				</p>~~<span id="cache-'.$pluginNameProcessed.'" style="font-weight:bold; line-height:20px;">
						Cache result?
						<input type="checkbox"  onchange="cachePlugin(\''.$pluginName.'\');" />
						</span>';
			}
		}
	}

	public function enablepluginAction() {
		$this->_helper->getHelper('layout')->disableLayout();
		$this->_helper->viewRenderer->setNoRender(true);
		//$this->checkLogin();
		$flag = true;
		$websiteUrl = $this->getWebSiteUrl();

		if($this->getRequest()->isPost() && $this->getRequest()->getParam('pluginName')) {
			$pluginName =  $this->getRequest()->getParam('pluginName');
			$pluginNameProcessed = str_replace(" ","-",$pluginName);
			if($pluginName && $pluginName!="") {
				$result = $this->_model->selectPluginByName($pluginName);
				if($result) {
					$pluginObj = new RCMS_Object_Plugin_Plugin($result['id']);
					$pluginObj->setStatus('enabled');
					$pluginObj->save();
					echo '<p  id="pluginstatus-'.$pluginNameProcessed.'">
					<button class="formsubmit" style="font-weight:bold;width:100px;font-size:12px;" onclick="disablePlugin(\''.$websiteUrl.'\',\''.$pluginName.'\')">Disable</button>
					</p>~~<span id="cache-'.$pluginNameProcessed.'" style="font-weight:bold; line-height:20px;">
						Cache result?
						<input type="checkbox"  onchange="cachePlugin(\''.$pluginName.'\');" />
						</span>';
				}else {
					if(file_exists("../public/plugins/".strtolower($pluginName)."/system/install.sql")) {
						$sql = file_get_contents("../public/plugins/".strtolower($pluginName)."/system/install.sql");
						if(trim($sql)) {

							$installation = $this->_model->executePluginSql($sql);
							if(!$installation) {
								$flag = true;
								echo "errors in sql";
								return;
							}
						}
					}else {
						$flag = false;
						echo "install.sql";
						return;
					}

					if($flag) {
						$newPlugin = new RCMS_Object_Plugin_Plugin();
						$newPlugin->setStatus("enabled");
						$newPlugin->setName($pluginName);
						$newPlugin->setCache(0);
						$newPlugin->save();
						echo '<p  id="pluginstatus-'.$pluginNameProcessed.'">
						<button class="formsubmit" style="font-weight:bold;width:100px;font-size:12px;" onclick="disablePlugin(\''.$websiteUrl.'\',\''.$pluginName.'\')">Disable</button>
						</p>~~<span id="cache-'.$pluginNameProcessed.'" style="font-weight:bold; line-height:20px;">
						Cache result?
						<input type="checkbox"  onchange="cachePlugin(\''.$pluginName.'\');" />
						</span>';
					}
				}
			}
		}
	}


	/**
	 * This function deletes a plugin from filesystem.
	 * @return void
	 */
	public function deletepluginAction() {
		$this->_helper->getHelper('layout')->disableLayout();
		$this->_helper->viewRenderer->setNoRender(true);

		if($this->getRequest()->isPost() &&
			$this->getRequest()->getParam('pluginName') != '' &&
			is_dir($this->pathPlugin . $this->getRequest()->getParam('pluginName'))) {

			$pluginName = strtolower($this->getRequest()->getParam('pluginName'));

			//uninstall.sql
			if(file_exists("../public/plugins/".$pluginName."/system/uninstall.sql")) {
				$sql = file_get_contents("../public/plugins/".$pluginName."/system/uninstall.sql");
				if(trim($sql)) {
					$uninstallation = $this->_model->executePluginSql($sql);
					if(!$uninstallation) {
						echo "errors in sql";
						return;
					}
					$this->_deletePluginFromTmpFolder($this->pathPlugin . $pluginName . '/');
				}
			}

			$result = $this->_model->selectPluginByName($pluginName);
			if($result) {
				$pluginObj = new RCMS_Object_Plugin_Plugin($result['id']);
				$pluginObj->delete();
			}

			//preg replace content
			$result = $this->_model->selectContentPairs();

			if($result) {
				foreach ($result as $content ) {
					$content['value'] = preg_replace('/{\$(plugin:'.$pluginName.'[\w\s-:,]*)}/', "", $content['value']);
					$this->_model->updateContent($content['id'],$content['value']);
				}
			}

			//preg replace tepmlates content
			$result = $this->_model->selectTemplates();
			$filesList = RCMS_Tools_FilesystemTools::scanDir($this->_pathThemes.$this->_currentThemeName);

			if($result) {
				foreach ($result as $template ) {
					$template['content'] = preg_replace('/{\$(plugin:'.$pluginName.'[\w\s-:,]*)}/', "", $template['content']);
					$this->_model->updateTemplate($template['id'],$template['content']);
					if(file_exists($this->_pathThemes.$this->_currentThemeName."/".$template['name'].".html")) {
						file_put_contents($this->_pathThemes.$this->_currentThemeName."/".$template['name'].".html", $template['content']);
					}
				}
			}




		}
	}
}