<?php

(!defined('IN_PowerBB')) ? die() : '';

define('IN_ADMIN',true);

$CALL_SYSTEM			        =	array();
$CALL_SYSTEM['ADDONS']         =   true;
$CALL_SYSTEM['HOOKS']         =   true;
$CALL_SYSTEM['STYLE'] 	= 	true;
$CALL_SYSTEM['TEMPLATE'] 	= 	true;
$CALL_SYSTEM['TEMPLATESEDITS'] 	= 	true;
define('JAVASCRIPT_PowerCode',true);

include('common.php');

define('CLASS_NAME','PowerBBAddonsMOD');

class PowerBBAddonsMOD
{

	function run()
	{
		global $PowerBB;

		if ($PowerBB->_CONF['member_permission'])
		{
			if ($PowerBB->_GET['control'])
			{
				$PowerBB->template->display('header');
				if ($PowerBB->_GET['main'])
				{
					$this->_ControlMain();
				}
			}
			elseif ($PowerBB->_GET['add'])
			{
				$PowerBB->template->display('header');

              	if ($PowerBB->_GET['main'])
				{
					$this->_AddAddonsMain();
				}
                elseif ($PowerBB->_GET['start'])
				{
					$this->_AddAddonsStart();
				}
			}
			elseif ($PowerBB->_GET['writing_addon'])
			{
				$PowerBB->template->display('header');

              	if ($PowerBB->_GET['main'])
				{
					$this->_WritingAddonsMain();
				}
                elseif ($PowerBB->_GET['start'])
				{
					$this->_WritingAddonsStart();
				}
			}
			elseif ($PowerBB->_GET['edit'])
			{
				$PowerBB->template->display('header');

				if ($PowerBB->_GET['main'])
				{
					$this->_EditMain();
				}
				elseif ($PowerBB->_GET['start'])
				{
					$this->_EditStart();
				}
			}
			elseif ($PowerBB->_GET['del'])
			{
				$PowerBB->template->display('header');

                if ($PowerBB->_GET['start'])
				{
					$this->_DelStart();
				}
			}
			elseif ($PowerBB->_GET['active'])
			{
                if ($PowerBB->_GET['start'])
				{
					$this->_ActiveStart();
				}
			}
			elseif ($PowerBB->_GET['no_active'])
			{
				$PowerBB->template->display('header');

                if ($PowerBB->_GET['start'])
				{
					$this->_NoActiveStart();
				}
			}
			elseif ($PowerBB->_GET['export'])
			{
                if ($PowerBB->_GET['start'])
				{
					$this->_ExportStart();
				}
				elseif ($PowerBB->_GET['export_writing'])
				{
					$this->_ExportWriting();
				}
			}
			elseif ($PowerBB->_GET['control_hooks'])
			{
				$PowerBB->template->display('header');

                if ($PowerBB->_GET['main'])
				{
					$this->_ControlHook();
				}
			}
			elseif ($PowerBB->_GET['edit_hook'])
			{
				$PowerBB->template->display('header');

                if ($PowerBB->_GET['main'])
				{
					$this->_MainEditHook();
				}
				elseif ($PowerBB->_GET['start'])
				{
					$this->_StartEditHook();
				}
			}


		$PowerBB->template->display('footer');
		}

	}


	/**
	 * add Addons Main
	 */

	function _AddAddonsMain()
	{
		global $PowerBB;

		$PowerBB->template->display('addons_add');

    }

	/**
	 * add Addons Start
	 */
	function _AddAddonsStart()
	{

		global $PowerBB;

		if (empty($PowerBB->_FILES['files']['name']))
		{
			$PowerBB->functions->error_no_foot($PowerBB->_CONF['template']['lang']['do_not_choose_to_file']);
		}

		$ext = $PowerBB->functions->GetFileExtension($PowerBB->_FILES['files']['name']);

		if ($ext != '.xml')
		{
			$PowerBB->functions->error_no_foot($PowerBB->_CONF['template']['lang']['error_xml_file']);
		}

		if ($PowerBB->addons->IsAddons(array('where' => array('name',$PowerBB->_FILES['files']['name']))))
		{
			$PowerBB->functions->error($PowerBB->_CONF['template']['lang']['error_extension'].' '.$PowerBB->_FILES['files']['name']. ' ' .$PowerBB->_CONF['template']['lang']['has_been_installed']);
		}


		$uploads_dir = 'addons';
		$uploaded = move_uploaded_file($PowerBB->_FILES['files']['tmp_name'] , $uploads_dir . '/' .$PowerBB->_FILES['files']['name']);

		if (!$uploaded)
		{
			$PowerBB->functions->error_no_foot($PowerBB->_CONF['template']['lang']['is_unable_permison_folder_addons'].' '.$PowerBB->_FILES['files']['tmp_name']);
		}

       	$xml_code = @file_get_contents('addons/'.$PowerBB->_FILES['files']['name']);
		$plugin = $PowerBB->addons->xml_to_array($xml_code);

		$name = $PowerBB->_FILES['files']['name'];
		$title = $plugin['plugin']['attributes']['name'];
		$version = $plugin['plugin']['version']['value'];
		$description = $plugin['plugin']['description']['value'];
		$author = $plugin['plugin']['author']['value'];
		$url = $plugin['plugin']['url']['value'];
		$new_module_index = $plugin['plugin']['new_module_index']['value'];
		$new_module_admin = $plugin['plugin']['new_module_admin']['value'];
		$installcode = $plugin['plugin']['installcode']['value'];
		$uninstallcode = $plugin['plugin']['uninstallcode']['value'];
		//LanguageValues
		$LanguageVals		= '';
		@eval($plugin['plugin']['languagevals']['value']);
		if ( is_array($AddonLangValues) )
		{
			$LanguageVals = addslashes(serialize($AddonLangValues));
		}
        eval($installcode);
		$installcode = str_replace("'","{sq}",$installcode);
		$uninstallcode = str_replace("'","{sq}",$uninstallcode);
        $installcode = preg_replace( "/\\\(?!&amp;#|\?#)/", "&#092;", $installcode );
        $uninstallcode = preg_replace( "/\\\(?!&amp;#|\?#)/", "&#092;", $uninstallcode );

		$new_module_index = str_replace("'","{sq}",$new_module_index);
		$new_module_admin = str_replace("'","{sq}",$new_module_admin);



		$AddonsArr 			= 	array();
		$AddonsArr['field']	=	array();

		$AddonsArr['field']['name'] 		    = 	$name;
		$AddonsArr['field']['title'] 		    = 	$title;
		$AddonsArr['field']['version'] 	    = 	$version;
		$AddonsArr['field']['description'] 	    	= 	$description;
		$AddonsArr['field']['author'] 		        = 	$author;
		$AddonsArr['field']['url'] 		            = 	$url;
		$AddonsArr['field']['module_index'] 	    = 	$new_module_index;
		$AddonsArr['field']['module_admin'] 	    = 	$new_module_admin;
		$AddonsArr['field']['installcode'] 		    = 	$installcode;
		$AddonsArr['field']['uninstallcode'] 	    = 	$uninstallcode;
		$AddonsArr['field']['languagevals']			=	$LanguageVals;

		$insert = $PowerBB->addons->InsertAddons($AddonsArr);

		$addon_arr = array();
		$addon_arr['where'] = array('name',$name);
		$addon_info = $PowerBB->addons->GetAddonsInfo($addon_arr);


		if ($insert){
	        	$PowerBB->functions->msg($PowerBB->_CONF['template']['lang']['addon_imported_successfully']);
			if($this->insert_hooks($plugin,$addon_info)){
				$PowerBB->functions->msg($PowerBB->_CONF['template']['lang']['eere_imported_hooks']);
			}
			elseif(!is_array($plugin['plugin']['hooks'])){
				$PowerBB->functions->msg($PowerBB->_CONF['template']['lang']['no_hooks_imported']);
			}


			if($this->edit_templates($plugin,$addon_info)){
				$PowerBB->functions->msg($PowerBB->_CONF['template']['lang']['was_modified_templates']);
			}
			if(!is_array($plugin['plugin']['templates'])){
				$PowerBB->functions->msg($PowerBB->_CONF['template']['lang']['no_modifications_templates']);
			}

			if($this->edit_templates_admin($plugin,$addon_info)){
				$PowerBB->functions->msg($PowerBB->_CONF['template']['lang']['was_modified_templates_admincp']);
			}
			if(!is_array($plugin['plugin']['admin_templates'])){
				$PowerBB->functions->msg($PowerBB->_CONF['template']['lang']['no_modifications_templates_admincp']);
			}
                $this->update_cache();


     	     	// Del All Cache Template
		       $Get_all_style = $PowerBB->DB->sql_query("SELECT  *   FROM " . $PowerBB->table['style'] . " WHERE id ");
		       while ($getstyle_row = $PowerBB->DB->sql_fetch_array($Get_all_style))
		       {

				if (is_dir($getstyle_row['cache_path']))
				{
					$dir = opendir($getstyle_row['cache_path']);

					if ($dir)
					{
						while (($file = readdir($dir)) !== false)
						{
							if ($file == '.'
								or $file == '..')
							{
								continue;
							}

							$del = unlink('./' . $getstyle_row['cache_path'] . '/' . $file);

						}

						closedir($dir);
					}
				}

			  }


				// Del All Cache Admin Templates
				$TemplatesList = 'look/styles/admin/main/compiler/';

				if (is_dir($TemplatesList))
				{
					$dir = opendir($TemplatesList);

					if ($dir)
					{
						while (($file = readdir($dir)) !== false)
						{
							if ($file == '.'
								or $file == '..')
							{
								continue;
							}

							$del = unlink('./' . $TemplatesList . $file);

						}

						closedir($dir);
					}
				 }

			$PowerBB->functions->redirect('admin.php?page=addons&amp;control=1&amp;main=1');
		}

	}

	/**
	 * Writing Addons Main
	 */

	function _WritingAddonsMain()
	{
		global $PowerBB;

        // show Addons List
		$AddonsArr 					= 	array();
		$AddonsArr['order']			=	array();
		$AddonsArr['order']['field']	=	'id';
		$AddonsArr['order']['type']	=	'DESC';
		$AddonsArr['proc'] 			= 	array();
		$AddonsArr['proc']['*'] 		= 	array('method'=>'clean','param'=>'html');

		$PowerBB->_CONF['template']['while']['AddonsList'] = $PowerBB->addons->GetAddonsList($AddonsArr);

		$PowerBB->template->display('addons_writing');

    }


	/**
	 * Writing Addons Start
	 */
	function _WritingAddonsStart()
	{

		global $PowerBB;

			$HooksArr 	=	array();
			$HooksArr['field']	=	array();
			$HooksArr['field']['addon_id']           =       $PowerBB->_POST['addons'];
			$HooksArr['field']['main_place']         =       $PowerBB->_POST['main_place'];
			$HooksArr['field']['place_of_hook']      =       $PowerBB->_POST['place_of_hook'];
			$HooksArr['field']['phpcode']	=	str_replace("'","{sq}",$PowerBB->_POST['phpcode']);

			$InsertHook = $PowerBB->hooks->InsertHooks($HooksArr);

			if ($InsertHook)
			{
	           $PowerBB->functions->msg($PowerBB->_CONF['template']['lang']['addon_added_successfully']);
			   $PowerBB->functions->redirect('admin.php?page=addons&amp;control_hooks=1&amp;main=1');
			}



	}

	function _ControlMain()
	{
		global $PowerBB;

        // show Addons List
		$AddonsArr 					= 	array();
		$AddonsArr['order']			=	array();
		$AddonsArr['order']['field']	=	'id';
		$AddonsArr['order']['type']	=	'DESC';
		$AddonsArr['proc'] 			= 	array();
		$AddonsArr['proc']['*'] 		= 	array('method'=>'clean','param'=>'html');

		$PowerBB->_CONF['template']['while']['AddonsList'] = $PowerBB->addons->GetAddonsList($AddonsArr);

		$PowerBB->template->display('addons_main');
	}


	function _EditMain()
	{
		global $PowerBB;
         /*
			if (empty($PowerBB->_GET['id']))
			{
				$PowerBB->functions->error($PowerBB->_CONF['template']['lang']['addon_requested_does_not_exist']);
			}

			$AddonsEditArr				=	array();
		    $AddonsEditArr['where'] 	= 	array('id',$PowerBB->_GET['id']);

			$AddonsEdit = $PowerBB->addons->GetAddonsInfo($AddonsEditArr);
			$PowerBB->template->assign('AddonsEdit',$AddonsEdit);

            $AddonsEdit['phpcode'] = str_replace('{sq}',"'",$AddonsEdit['phpcode']);
            $PowerBB->template->assign('phpcode',$AddonsEdit['phpcode']);

            $AddonsEdit['installcode'] = str_replace('{sq}',"'",$AddonsEdit['installcode']);
            $PowerBB->template->assign('installcode',$AddonsEdit['installcode']);

            $AddonsEdit['uninstallcode'] = str_replace('{sq}',"'",$AddonsEdit['uninstallcode']);
            $PowerBB->template->assign('uninstallcode',$AddonsEdit['uninstallcode']);

            $AddonsEdit['hookname'] = str_replace('.tpl','',$AddonsEdit['hookname']);
            $PowerBB->template->assign('hookname',$AddonsEdit['hookname']);

		$PowerBB->template->display('addons_edit');
		*/
			$PowerBB->functions->msg($PowerBB->_CONF['template']['lang']['property_addon_editing_is_off']);
			$PowerBB->functions->redirect('admin.php?page=addons&amp;control=1&amp;main=1');


	}

	function _EditStart()
	{
		global $PowerBB;
        /*

			if (empty($PowerBB->_GET['id']))
			{
				$PowerBB->functions->error($PowerBB->_CONF['template']['lang']['addon_requested_does_not_exist']);
			}

		    $AddonsInfoArr				=	array();
		    $AddonsInfoArr['where'] 	= 	array('id',$PowerBB->_GET['id']);

			$AddonsInfo = $PowerBB->addons->GetAddonsInfo($AddonsInfoArr);
		    $del_file = @unlink('addons/'.$AddonsInfo['name']);

		$PowerBB->_POST['installcode'] = str_replace("'","{sq}",$PowerBB->_POST['installcode']);
		$PowerBB->_POST['uninstallcode'] = str_replace("'","{sq}",$PowerBB->_POST['uninstallcode']);

		$AddonsArr 			= 	array();
		$AddonsArr['field']	=	array();

		$AddonsArr['field']['name']             =       $PowerBB->_POST['name'];
		$AddonsArr['field']['title']            =       $PowerBB->_POST['title'];
		$AddonsArr['field']['version'] 		    =       $PowerBB->_POST['version'];
		$AddonsArr['field']['description'] 	    =       $PowerBB->_POST['description'];
		$AddonsArr['field']['author'] 	    	=       $PowerBB->_POST['author'];
		$AddonsArr['field']['url'] 		        =       $PowerBB->_POST['url'];
		$AddonsArr['field']['installcode'] 		=       $PowerBB->_POST['installcode'];
		$AddonsArr['field']['uninstallcode'] 	=       $PowerBB->_POST['uninstallcode'];
		$AddonsArr['field']['active'] 		    =       $PowerBB->_POST['active'];
		$AddonsArr['where'] 				    = 	array('id',$PowerBB->_GET['id']);

		$update = $PowerBB->addons->UpdateAddons($AddonsArr);

		if ($update)
		{

	          $start_xml = '<?xml version="1.0" encoding="ISO-8859-1"?>
	          ';
	          $x_title = '<title>'.$PowerBB->_POST['title'].'</title>
	          ';
	          $x_installcode = '<installcode><![CDATA['.$PowerBB->_POST['installcode'].']]></installcode>
	          ';
	          $x_uninstallcode = '<uninstallcode><![CDATA['.$PowerBB->_POST['uninstallcode'].']]></uninstallcode>
	          ';
	          $x_version = '<version>'.$PowerBB->_POST['version'].'</version>
	          ';
	          $x_description = '<description>'.$PowerBB->_POST['description'].'</description>
	          ';
	          $x_url = '<url>'.$PowerBB->_POST['url'].'</url>
	          ';
	          $x_author = '<author>'.$PowerBB->_POST['author'].'</author>
	          ';

	          $context = $start_xml.$x_hookname.$x_title.$x_phpcode.$x_installcode.$x_uninstallcode.$x_version.$x_description.$x_url.$x_author ;
              $context = str_replace('\'"',"'", $context);
              $context = str_replace('\\"','"', $context);
              $context = str_replace("\\'","'", $context);
              $context = str_replace('{sq}',"'", $context);

	          $uploads_dir = 'addons';
		      $fp = fopen($uploads_dir . '/' . $PowerBB->_POST['name'],'w');
		      $fw = fwrite($fp,$context);
		      fclose($fp);


			$PowerBB->functions->msg($PowerBB->_CONF['template']['lang']['addon_updated_successfully']);
			$PowerBB->functions->redirect('admin.php?page=addons&amp;control=1&amp;main=1');
		}
		*/
			$PowerBB->functions->msg($PowerBB->_CONF['template']['lang']['property_addon_editing_is_off']);

	   $PowerBB->functions->redirect('admin.php?page=addons&amp;control=1&amp;main=1');

	}

	function _DelStart()
	{
		global $PowerBB;

			if (empty($PowerBB->_GET['id']))
			{
				$PowerBB->functions->error($PowerBB->_CONF['template']['lang']['addon_requested_does_not_exist']);
			}
			$AddonsInfoArr				=	array();
		    	$AddonsInfoArr['where'] 	= 	array('id',$PowerBB->_GET['id']);

			$AddonsInfo = $PowerBB->addons->GetAddonsInfo($AddonsInfoArr);

		    	$del_file = @unlink('addons/'.$AddonsInfo['name']);

			$DelArr 			= 	array();
			$DelArr['where'] 	= 	array('id',$PowerBB->_GET['id']);

			$del = $PowerBB->addons->DeleteAddons($DelArr);

			if ($del && $del_file)
			{
				$uninstallcode = $AddonsInfo['uninstallcode'];
				$uninstallcode = str_replace("{sq}","'",$uninstallcode);
                $uninstallcode = str_replace( "&#092;", "\\", $uninstallcode);
                eval($uninstallcode);

				if($this->del_hooks($AddonsInfo)){
					$PowerBB->functions->msg($PowerBB->_CONF['template']['lang']['deleted_hooks_successfully']);
				}
				if($this->back_templates($AddonsInfo))
				{
					$PowerBB->functions->msg($PowerBB->_CONF['template']['lang']['templates_inauguration_Added']);
				}


				      // Del All Cache Template
				       $Get_all_style = $PowerBB->DB->sql_query("SELECT  *   FROM " . $PowerBB->table['style'] . " WHERE id ");
				       while ($getstyle_row = $PowerBB->DB->sql_fetch_array($Get_all_style))
				       {

						if (is_dir($getstyle_row['cache_path']))
						{
							$dir = opendir($getstyle_row['cache_path']);

							if ($dir)
							{
								while (($file = readdir($dir)) !== false)
								{
									if ($file == '.'
										or $file == '..')
									{
										continue;
									}

									$del = unlink('./' . $getstyle_row['cache_path'] . '/' . $file);

								}

								closedir($dir);
							}
						}

					  }

						// Del All Cache Admin Templates
						$TemplatesList = 'look/styles/admin/main/compiler/';

						if (is_dir($TemplatesList))
						{
							$dir = opendir($TemplatesList);

							if ($dir)
							{
								while (($file = readdir($dir)) !== false)
								{
									if ($file == '.'
										or $file == '..')
									{
										continue;
									}

									$del = unlink('./' . $TemplatesList . $file);

								}

								closedir($dir);
							}
						}

				$PowerBB->functions->msg($PowerBB->_CONF['template']['lang']['addon_delet_successfully']);
				$PowerBB->functions->redirect('admin.php?page=addons&amp;control=1&amp;main=1');
			}
	}

	function _ActiveStart()
	{
		global $PowerBB;

			if (empty($PowerBB->_GET['id']))
			{
				$PowerBB->functions->error($PowerBB->_CONF['template']['lang']['addon_requested_does_not_exist']);
			}
		$addon_arr = array();
		$addon_arr['where'] = array('id',$PowerBB->_GET['id']);
		$addon_info = $PowerBB->addons->GetAddonsInfo($addon_arr);

       	$xml_code = @file_get_contents('addons/'.$addon_info['name']);
		$plugin = $PowerBB->addons->xml_to_array($xml_code);

		$name = $addon_info['name'];
		$title = $plugin['plugin']['attributes']['name'];
		$version = $plugin['plugin']['version']['value'];
		$description = $plugin['plugin']['description']['value'];
		$author = $plugin['plugin']['author']['value'];
		$url = $plugin['plugin']['url']['value'];



	        $PowerBB->functions->msg($PowerBB->_CONF['template']['lang']['addon_activated_successfully']);
			if($this->insert_hooks($plugin,$addon_info)){
				$PowerBB->functions->msg($PowerBB->_CONF['template']['lang']['eere_imported_hooks']);
			}
			elseif(!is_array($plugin['plugin']['hooks'])){
				$PowerBB->functions->msg($PowerBB->_CONF['template']['lang']['no_hooks_imported']);
			}


			if($this->edit_templates($plugin,$addon_info)){
				$PowerBB->functions->msg($PowerBB->_CONF['template']['lang']['was_modified_templates']);
			}
			if(!is_array($plugin['plugin']['templates'])){
				$PowerBB->functions->msg($PowerBB->_CONF['template']['lang']['no_modifications_templates']);
			}

			if($this->edit_templates_admin($plugin,$addon_info)){
				$PowerBB->functions->msg($PowerBB->_CONF['template']['lang']['was_modified_templates_admincp']);
			}
			if(!is_array($plugin['plugin']['admin_templates'])){
				$PowerBB->functions->msg($PowerBB->_CONF['template']['lang']['no_modifications_templates_admincp']);
			}

                $this->update_cache();


     	     	// Del All Cache Template
		       $Get_all_style = $PowerBB->DB->sql_query("SELECT  *   FROM " . $PowerBB->table['style'] . " WHERE id ");
		       while ($getstyle_row = $PowerBB->DB->sql_fetch_array($Get_all_style))
		       {

				if (is_dir($getstyle_row['cache_path']))
				{
					$dir = opendir($getstyle_row['cache_path']);

					if ($dir)
					{
						while (($file = readdir($dir)) !== false)
						{
							if ($file == '.'
								or $file == '..')
							{
								continue;
							}

							$del = unlink('./' . $getstyle_row['cache_path'] . '/' . $file);

						}

						closedir($dir);
					}
				}

			  }


				// Del All Cache Admin Templates
				$TemplatesList = 'look/styles/admin/main/compiler/';

				if (is_dir($TemplatesList))
				{
					$dir = opendir($TemplatesList);

					if ($dir)
					{
						while (($file = readdir($dir)) !== false)
						{
							if ($file == '.'
								or $file == '..')
							{
								continue;
							}

							$del = unlink('./' . $TemplatesList . $file);

						}

						closedir($dir);
					}
				 }

		$AddonsArr 			= 	array();
		$AddonsArr['field']	=	array();

		$AddonsArr['field']['active'] 		    =       '1';
		$AddonsArr['where'] 				    = 	array('id',$PowerBB->_GET['id']);

		$update = $PowerBB->addons->UpdateAddons($AddonsArr);

		if ($update)
		{
			$PowerBB->functions->msg($PowerBB->_CONF['template']['lang']['addon_activated_successfully']);
			$PowerBB->functions->redirect('admin.php?page=addons&amp;control=1&amp;main=1');
		}
	}

	function _NoActiveStart()
	{
		global $PowerBB;

			if (empty($PowerBB->_GET['id']))
			{
				$PowerBB->functions->error($PowerBB->_CONF['template']['lang']['addon_requested_does_not_exist']);
			}
			    $AddonsInfoArr				=	array();
		    	$AddonsInfoArr['where'] 	= 	array('id',$PowerBB->_GET['id']);

			$AddonsInfo = $PowerBB->addons->GetAddonsInfo($AddonsInfoArr);


				if($this->del_hooks($AddonsInfo)){
					$PowerBB->functions->msg($PowerBB->_CONF['template']['lang']['addon_hooks_disabled_successfully']);
				}
				if($this->back_templates($AddonsInfo)){
					$PowerBB->functions->msg($PowerBB->_CONF['template']['lang']['addon_hooks_disabled_successfully']);
				}
				      // Del All Cache Template
				       $Get_all_style = $PowerBB->DB->sql_query("SELECT  *   FROM " . $PowerBB->table['style'] . " WHERE id ");
				       while ($getstyle_row = $PowerBB->DB->sql_fetch_array($Get_all_style))
				       {

						if (is_dir($getstyle_row['cache_path']))
						{
							$dir = opendir($getstyle_row['cache_path']);

							if ($dir)
							{
								while (($file = readdir($dir)) !== false)
								{
									if ($file == '.'
										or $file == '..')
									{
										continue;
									}

									$del = unlink('./' . $getstyle_row['cache_path'] . '/' . $file);

								}

								closedir($dir);
							}
						}

					  }

						// Del All Cache Admin Templates
						$TemplatesList = 'look/styles/admin/main/compiler/';

						if (is_dir($TemplatesList))
						{
							$dir = opendir($TemplatesList);

							if ($dir)
							{
								while (($file = readdir($dir)) !== false)
								{
									if ($file == '.'
										or $file == '..')
									{
										continue;
									}

									$del = unlink('./' . $TemplatesList . $file);

								}

								closedir($dir);
							}
						}

		$AddonsArr 			= 	array();
		$AddonsArr['field']	=	array();

		$AddonsArr['field']['active'] 		    =       '0';
		$AddonsArr['where'] 				    = 	array('id',$PowerBB->_GET['id']);

		$update = $PowerBB->addons->UpdateAddons($AddonsArr);

		if ($update)
		{
			$PowerBB->functions->msg($PowerBB->_CONF['template']['lang']['addon_disabled_successfully']);
			$PowerBB->functions->redirect('admin.php?page=addons&amp;control=1&amp;main=1');
		}
	}

	function _ExportStart()
	{
		global $PowerBB;

		$PowerBB->_GET['id'] = $PowerBB->functions->CleanVariable($PowerBB->_GET['id'],'intval');

		if (empty($PowerBB->_GET['id']))
		{
			$PowerBB->functions->error($PowerBB->_CONF['template']['lang']['message']);
		}


		$AddonsInfoArr				=	array();
	    $AddonsInfoArr['where'] 	= 	array('id',$PowerBB->_GET['id']);

		$AddonsInfo = $PowerBB->addons->GetAddonsInfo($AddonsInfoArr);

		if ($AddonsInfo)
		{

			$Adress	= 	$PowerBB->functions->GetForumAdress();
		   $filename = $Adress.'addons/'.$AddonsInfo['name'];
           header("Content-Disposition: attachment;filename=" . $AddonsInfo['name'] . "");
		   header('Content-type: application/download');
          $read = @readfile($filename);
		   exit;
		}

	}

	function _ExportWriting()
	{
		global $PowerBB;

         $PowerBB->_POST['context'] = str_replace('\\"', '"', $PowerBB->_POST['context']);
         $PowerBB->_POST['context'] = str_replace("\\'", "'", $PowerBB->_POST['context']);

           $uploads_dir = 'addons';
	       $fp = fopen($uploads_dir . '/' . $PowerBB->_GET['xml_name'],'w');
	       $fw = fwrite($fp,$PowerBB->_POST['context']);
	       fclose($fp);
		if ($fp)
		{
          $Adress	= 	$PowerBB->functions->GetForumAdress();
		  $filename = $Adress.'addons/'.$PowerBB->_GET['xml_name'];
          header("Content-Disposition: attachment;filename=" . $PowerBB->_GET['xml_name'] . "");
		  header('Content-type: application/download');
          $read = @readfile($filename);
		  exit;
       }
	}


	function insert_hooks($xml_array,$inserted_plugin_info)
	{
		global $PowerBB;

		if(!is_array($xml_array['plugin']['hooks']) or !isset($xml_array['plugin']['hooks']['hook'][0])){
			return FALSE;
		}

		else{
			$hooks = $xml_array['plugin']['hooks']['hook'];

			foreach($hooks as $hook){

			$HooksArr 	=	array();
			$HooksArr['field']	=	array();
			$HooksArr['field']['addon_id']	=	$inserted_plugin_info['id'];
			$HooksArr['field']['main_place']	=	$hook['attributes']['main_place'];
			$HooksArr['field']['place_of_hook']	=	$hook['attributes']['place'];
			$HooksArr['field']['phpcode']	=	str_replace("'","{sq}",$hook['value']);

			$InsertHook = $PowerBB->hooks->InsertHooks($HooksArr);

			}
			if($InsertHook){
				return TRUE;
			}
			else{
				return FALSE;
			}
		}

	}
	//Edited--------------------------------------------------------
	//Original Line	function edit_templates($xml_array,$plugin_info)
	function edit_templates($xml_array,$plugin_info,$SpecificStyle='')	//specific style's id
	{
		global $PowerBB;

		if (intval($SpecificStyle) < 1)
		{
			$StyleList = $PowerBB->style->GetStyleList(array());
		}
		else
		{
			$StyleList = $PowerBB->style->GetStyleList(array('where' => array('id',$SpecificStyle)));
		}
		//---------------------------------------------------------------
		$Templates = $xml_array['plugin']['templates']['template'];

      if($Templates)
	 {
		if(!isset($xml_array['plugin']['templates']['template'][1]))
		{
			$find = $Templates['find']['value'];
			$action = $Templates['action']['value'];
        	$find	=	str_replace("'","{sq}",$find);
        	$action	=	str_replace("'","{sq}",$action);
            $find = preg_replace( "/\\\(?!&amp;#|\?#)/", "&#092;", $find );
            $action = preg_replace( "/\\\(?!&amp;#|\?#)/", "&#092;", $action );

			$TemplateseditsArr	=	array();
			$TemplateseditsArr['field']	=	array();
			$TemplateseditsArr['field']['addon_id']	=	$plugin_info['id'];
			$TemplateseditsArr['field']['template_name']	=	$Templates['attributes']['name'];
			$TemplateseditsArr['field']['action']	=	$Templates['attributes']['type'];
			$TemplateseditsArr['field']['old_text']	=	$find;
			$TemplateseditsArr['field']['text']	=	$action;

			$Insert = $PowerBB->templates_edits->InsertTemplatesEdits($TemplateseditsArr);

			foreach($StyleList as $Style)
			 {
				if($Templates['attributes']['type'] != 'new')
				{
					$Path = $Style['template_path'].'/'.$Templates['attributes']['name'];
					if(file_exists($Path)){

					$contents = @file_get_contents($Path);

					$new = $PowerBB->addons->replacer($Templates['attributes']['type'],$contents,$Templates['find']['value'],$Templates['action']['value']);

					$put = @file_put_contents($Path,$new);
					}
				 }
			    if($Templates['attributes']['type'] == 'new')
				{
					$Path = $Style['template_path'].'/'.$Templates['attributes']['name'];

					if(!file_exists($Path))
					{
						$new = fopen($Path,'x');

						fwrite($new,$Templates['text']['value']);

						fclose($new);
					}
				}
			}
		}
		else
		{

		foreach($Templates as $Template)
		 {

			$find = $Template['find']['value'];
			$action = $Template['action']['value'];
        	$find	=	str_replace("'","{sq}",$find);
        	$action	=	str_replace("'","{sq}",$action);
            $find = preg_replace( "/\\\(?!&amp;#|\?#)/", "&#092;", $find );
            $action = preg_replace( "/\\\(?!&amp;#|\?#)/", "&#092;", $action );

			$TemplateseditsArr	=	array();
			$TemplateseditsArr['field']	=	array();
			$TemplateseditsArr['field']['addon_id']	=	$plugin_info['id'];
			$TemplateseditsArr['field']['template_name']	=	$Template['attributes']['name'];
			$TemplateseditsArr['field']['action']	=	$Template['attributes']['type'];
			$TemplateseditsArr['field']['old_text']	=	$find;
			$TemplateseditsArr['field']['text']	=	$action;

			$Insert = $PowerBB->templates_edits->InsertTemplatesEdits($TemplateseditsArr);

			foreach($StyleList as $Style)
			 {
				if($Template['attributes']['type'] != 'new')
				{
					$Path = $Style['template_path'].'/'.$Template['attributes']['name'];
					if(file_exists($Path)){

					$contents = @file_get_contents($Path);

					$new = $PowerBB->addons->replacer($Template['attributes']['type'],$contents,$Template['find']['value'],$Template['action']['value']);

					$put = @file_put_contents($Path,$new);
					}
				 }
			    if($Template['attributes']['type'] == 'new')
				{
					$Path = $Style['template_path'].'/'.$Template['attributes']['name'];

					if(!file_exists($Path))
					{
						$new = fopen($Path,'x');

						fwrite($new,$Template['text']['value']);

						fclose($new);
					}
				}
			}


		}
       }
		if($Insert && $put)
		{
			return TRUE;
		}
      }
	}

	function edit_templates_admin($xml_array,$plugin_info)
	{
		global $PowerBB;

		$Templates = $xml_array['plugin']['admin_templates']['template'];
      if($Templates)
	 {
		if(!isset($xml_array['plugin']['admin_templates']['template'][1]))
		{
			$find = $Templates['find']['value'];
			$action = $Templates['action']['value'];
        	$find	=	str_replace("'","{sq}",$find);
        	$action	=	str_replace("'","{sq}",$action);
            $find = preg_replace( "/\\\(?!&amp;#|\?#)/", "&#092;", $find );
            $action = preg_replace( "/\\\(?!&amp;#|\?#)/", "&#092;", $action );

			$TemplateseditsArr	=	array();
			$TemplateseditsArr['field']	=	array();
			$TemplateseditsArr['field']['addon_id']	=	$plugin_info['id'];
			$TemplateseditsArr['field']['template_name']	=	$Templates['attributes']['name'];
			$TemplateseditsArr['field']['action']	=	$Templates['attributes']['type'];
			$TemplateseditsArr['field']['old_text']	=	$find;
			$TemplateseditsArr['field']['text']	=	$action;

			$Insert = $PowerBB->templates_edits->InsertTemplatesEdits($TemplateseditsArr);

			if($Templates['attributes']['type'] != 'new')
				{
					$Path = 'look/styles/admin/main/templates/'.$Templates['attributes']['name'];
					if(file_exists($Path)){

					$contents = @file_get_contents($Path);

					$new = $PowerBB->addons->replacer($Templates['attributes']['type'],$contents,$Templates['find']['value'],$Templates['action']['value']);

					$put = @file_put_contents($Path,$new);
					}
				 }
			    if($Templates['attributes']['type'] == 'new')
				{
					$Path = 'look/styles/admin/main/templates/'.$Templates['attributes']['name'];

					if(!file_exists($Path))
					{
						$new = fopen($Path,'x');

						fwrite($new,$Templates['text']['value']);

						fclose($new);
					}
				}
		}
		else
		{
		  foreach($Templates as $Template)
		   {

			$find = $Template['find']['value'];
			$action = $Template['action']['value'];
        	$find	=	str_replace("'","{sq}",$find);
        	$action	=	str_replace("'","{sq}",$action);
            $find = preg_replace( "/\\\(?!&amp;#|\?#)/", "&#092;", $find );
            $action = preg_replace( "/\\\(?!&amp;#|\?#)/", "&#092;", $action );

			$TemplateseditsArr	=	array();
			$TemplateseditsArr['field']	=	array();
			$TemplateseditsArr['field']['addon_id']	=	$plugin_info['id'];
			$TemplateseditsArr['field']['template_name']	=	$Template['attributes']['name'];
			$TemplateseditsArr['field']['action']	=	$Template['attributes']['type'];
			$TemplateseditsArr['field']['old_text']	=	$find;
			$TemplateseditsArr['field']['text']	=	$action;

			$Insert = $PowerBB->templates_edits->InsertTemplatesEdits($TemplateseditsArr);

			if($Template['attributes']['type'] != 'new')
				{
					$Path = 'look/styles/admin/main/templates/'.$Template['attributes']['name'];
					if(file_exists($Path)){

					$contents = @file_get_contents($Path);

					$new = $PowerBB->addons->replacer($Template['attributes']['type'],$contents,$Template['find']['value'],$Template['action']['value']);

					$put = @file_put_contents($Path,$new);
					}
				 }
			    if($Template['attributes']['type'] == 'new')
				{
					$Path = 'look/styles/admin/main/templates/'.$Template['attributes']['name'];

					if(!file_exists($Path))
					{
						$new = fopen($Path,'x');

						fwrite($new,$Template['text']['value']);

						fclose($new);
					}
				}

		   }
        }
		if($Insert && $put)
		{
			return TRUE;
		}
      }
	}

	function del_hooks($plugin_info)
	{

		global $PowerBB;

		if(empty($plugin_info) or !isset($plugin_info['id'])){

			return FALSE;

		}
		else{

		$HooksList = $PowerBB->hooks->GetHooksList(array('where'=>array('addon_id',$plugin_info['id'])));

		foreach($HooksList as $Hook){

			$Delete = $PowerBB->hooks->DeleteHooks(array('where'=>array('addon_id',$plugin_info['id'])));

			if($Delete){

				return TRUE;

			}
			else
			{
				return FALSE;
			}
		}
		}
	}
	//Edited--------------------------------------------------------
	//Original Line	function :: function back_templates($plugin_info)
	function back_templates($plugin_info,$SpecificStyle='')	//specific style's id
	{
		global $PowerBB;

		$TemplateseditsList = $PowerBB->templates_edits->GetTemplatesEditsList(array('where'=>array('addon_id',$plugin_info['id'])));

		if (intval($SpecificStyle) < 1)
		{
			$StyleList = $PowerBB->style->GetStyleList(array());
		}
		else
		{
			$StyleList = $PowerBB->style->GetStyleList(array('where' => array('id',$SpecificStyle)));
		}
		//---------------------------------------------------------------
		foreach($TemplateseditsList as $Templatesedits){


			foreach($StyleList as $Style)
			{
            $old_text = $Templatesedits['old_text'];
            $text = $Templatesedits['text'];

			$old_text = str_replace("{sq}","'",$old_text);
			$text = str_replace("{sq}","'",$text);
            $old_text = str_replace( "&#092;", "\\", $old_text);
            $text = str_replace( "&#092;", "\\", $text);

			$Path = $Style['template_path'].'/'.$Templatesedits['template_name'];
			$PathAdmin = 'look/styles/admin/main/templates/'.$Templatesedits['template_name'];
			if($Templatesedits['action'] == 'new'){

				$del = @unlink($Path);
				$delAdmin = @unlink($PathAdmin);

			}
			elseif($Templatesedits['action'] != 'replace'){
            if(file_exists($Path)){
			$content = @file_get_contents($Path);
			$new = @str_replace($text,'',$content);
			$put = @file_put_contents($Path,$new);
            }
			}

			else{
            if(file_exists($Path)){
			$contents = @file_get_contents($Path);
			$new_contents = $PowerBB->addons->replacer('replace',$contents,$text,$old_text);
			$put = @file_put_contents($Path,$new_contents);
            }
			}

			}

			$PathAdmin = 'look/styles/admin/main/templates/'.$Templatesedits['template_name'];
           if($Templatesedits['action'] != 'replace'){
            if(file_exists($PathAdmin)){
			$contentAdmin = @file_get_contents($PathAdmin);
			$newAdmin = @str_replace($text,'',$contentAdmin);
			$putAdmin = @file_put_contents($PathAdmin,$newAdmin);
			}
			}
			else
			{
            if(file_exists($PathAdmin)){
			$contentsAdmin = @file_get_contents($PathAdmin);
			$new_contentsAdmin = $PowerBB->addons->replacer('replace',$contentsAdmin,$text,$old_text);
			$putAdmin = @file_put_contents($PathAdmin,$new_contentsAdmin);
            }
			}
			$Delete = $PowerBB->templates_edits->DeleteTemplatesEdits(array('where'=>array('id',$Templatesedits['id'])));

		}


		if($Delete && $put){

			return TRUE;
		}

	}


	function update_cache(){
		global $PowerBB;

		$HooksList = $PowerBB->hooks->GetHooksList(array());


			$data = '<?php
/*
*
*@packacge : Hooks Cache
*@author : ExchangeBoss (ShadiMashaqi)
*@version : 1.0.0
*@start : 24/2/2010
*@end : (Updated By Php)
*/


$Hooks = array();


';

		foreach($HooksList as $Hook){

			$AddonInfo = $PowerBB->addons->GetAddonsInfo(array('where'=>array('id',$Hook['addon_id'])));

			if($AddonInfo['active'] == '1'){


			$data .= '$Hooks[\''.$Hook['main_place'].'\'][\''.$Hook['place_of_hook'].'\'] = \''.str_replace("{sq}","\'",str_replace("'","\'",$Hook['phpcode']))."';\n\n\n";


			}

		}

		$data .= "\n\n".'//end of cache file'."\n";
		$data .= '?>';
		$open = fopen('includes/HooksCache.php','w');
		fwrite($open,$data);
		fclose($open);


	}


	function _ControlHook()
	{
		global $PowerBB;

        // show Addons List
		$HooksArr 					= 	array();
		$HooksArr['order']			=	array();
		$HooksArr['order']['field']	=	'id';
		$HooksArr['order']['type']	=	'DESC';
		$HooksArr['proc'] 			= 	array();
		$HooksArr['proc']['*'] 		= 	array('method'=>'clean','param'=>'html');

		$PowerBB->_CONF['template']['while']['HooksList'] = $PowerBB->hooks->GetHooksList($HooksArr);

		$PowerBB->template->display('hooks_main');
	}

	function _MainEditHook()
	{
		global $PowerBB;

		$HooksInfoArr				=	array();
	    $HooksInfoArr['where'] 	= 	array('id',$PowerBB->_GET['id']);

		$HooksInfo = $PowerBB->hooks->GetHooksInfo($HooksInfoArr);

        $PowerBB->template->assign('HooksInfo',$HooksInfo);

        // show Addons List
		$HooksArr 					= 	array();
		$HooksArr['order']			=	array();
		$HooksArr['order']['field']	=	'id';
		$HooksArr['order']['type']	=	'DESC';
		$HooksArr['proc'] 			= 	array();
		$HooksArr['proc']['*'] 		= 	array('method'=>'clean','param'=>'html');

		$PowerBB->_CONF['template']['while']['HooksList'] = $PowerBB->hooks->GetHooksList($HooksArr);

        $Addonid =  $PowerBB->_GET['id'];
        // show Addons List
		$AddonsArr 					= 	array();
		$AddonsArr['order']			=	array();
		$AddonsArr['order']['field']	=	'id';
		$AddonsArr['order']['type']	=	'DESC';

		$AddonsArr = array();
		$AddonsArr['where'] 				= 	array();
		$AddonsArr['where'][0] 			= 	array();
		$AddonsArr['where'][0]['name'] 	= 	'id not in ('.$Addonid.') AND active';
		$AddonsArr['where'][0]['oper'] 	= 	'=';
		$AddonsArr['where'][0]['value'] 	= 	'0';

		$AddonsArr['proc'] 			= 	array();
		$AddonsArr['proc']['*'] 		= 	array('method'=>'clean','param'=>'html');

		$PowerBB->_CONF['template']['while']['AddonsList'] = $PowerBB->addons->GetAddonsList($AddonsArr);

		$PowerBB->template->display('hook_edit');
	}

	function _StartEditHook()
	{
		global $PowerBB;
		$PowerBB->_GET['id'] = $PowerBB->functions->CleanVariable($PowerBB->_GET['id'],'intval');

		if (empty($PowerBB->_GET['id']))
		{
			$PowerBB->functions->error($PowerBB->_CONF['template']['lang']['plugin_does_not_exist']);
		}

		$HooksInfoArr				=	array();
	    $HooksInfoArr['where'] 	= 	array('id',$PowerBB->_GET['id']);

		$HooksInfo = $PowerBB->hooks->GetHooksInfo($HooksInfoArr);

		$HookArr 			= 	array();
		$HookArr['field']	=	array();

		$HookArr['field']['addon_id']           =       $PowerBB->_POST['addons'];
		$HookArr['field']['main_place']         =       $PowerBB->_POST['main_place'];
		$HookArr['field']['place_of_hook']      =       $PowerBB->_POST['place_of_hook'];
		$HookArr['field']['phpcode'] 		    =       $PowerBB->_POST['phpcode'];
		$HookArr['where'] 				        = 	array('id',$PowerBB->_GET['id']);

		$update = $PowerBB->hooks->UpdateHooks($HookArr);


			$PowerBB->functions->msg($PowerBB->_CONF['template']['lang']['plugin_updated_successfully']);
			$PowerBB->functions->redirect('admin.php?page=addons&amp;control_hooks=1&amp;main=1');
	}

}

?>
