<?php
/**
 * This file contains the base class for all addons to do their work.
 * Addons must extend this class as it contains basic functionality they will require.
 *
 * @package Interspire_Addons, Fromnameandemail Addon
 */

/**
 * Addons_add_addon_installer
 * This is the base class for all addons to work off.
 * It handles:
 * - installing & uninstalling addons
 * - enabling & disabling addons
 * - running addons
 * - finding/loading addons including their language files and description.xml files
 *
 * The description.xml file is used by the calling code to work out
 * - the name of the addon
 * - a short description
 * - the current version number
 * - the author
 * - license details
 *
 * @uses Interspire_Addons_Exception, Fromnameandemail Addon
 */

if (! class_exists('Interspire_Addons', false)) { require_once (dirname(dirname(__FILE__)) . '/interspire_addons.php'); }
require_once (dirname(__FILE__) . '/language/language.php');
class Addons_customheader extends Interspire_Addons{
    private $AddonName = "customheader";
	
	public function Install()
	{
		$tables = $sequences = array();
		$this->db->StartTransaction();
		
		require dirname(__FILE__) . '/schema.' . SENDSTUDIO_DATABASE_TYPE . '.php';
		foreach ($queries as $query) {
			$qry = str_replace('%%TABLEPREFIX%%', $this->db->TablePrefix, $query);
			$result = $this->db->Query($qry);
			if (!$result) {
				$this->db->RollbackTransaction();
				throw new Interspire_Addons_Exception("There was a problem running query " . $qry . ": " . $this->db->GetErrorMsg(), Interspire_Addons_Exception::DatabaseError);
			}
		}
		$temp_path = IEM_ADDONS_PATH . "/customheader/modifier/existing/";
		if(!is_dir($temp_path)){
			throw new Interspire_Addons_Exception("ERROR: Directory {$temp_path} is not exists", Interspire_Addons_Exception::AddonDoesntExist);
		}
		if (!is_writable($temp_path)){
            throw new Interspire_Addons_Exception("ERROR: Folder {$temp_path} is not writable", Interspire_Addons_Exception::AddonDoesntExist);
        }
		$this->enabled = true;
		$this->configured = true;
		$this->installAddonFiles('customheader');
        try {
			$status = parent::Install();
		} catch (Interspire_Addons_Exception $e) {
			$this->db->RollbackTransaction();
			throw new Exception("Unable to install addon {$this->GetId()} " . $e->getMessage());
		}

		$this->db->CommitTransaction();

		return true;
	}

	
	/**
	 * UnInstall
	 * Drop tables the addon created.
	 * It includes the schema files (based on the database type) and drops the bits it created.
	 * Once that's done, it calls the parent UnInstall method to do its work.
	 *
	 * @uses Interspire_Addons::UnInstall
	 * @uses Interspire_Addons_Exception
	 *
	 * @return Returns true if the addon was uninstalled successfully.
	 * @throws Throws an Interspire_Addons_Exception::DatabaseError if one of the tables it created couldn't be removed. If the parent::UnInstall method throws an exception, this will
	 * just re-throw that error.
	 */
	public function UnInstall()
	{
		$tables = $sequences = array();

		$this->db->StartTransaction();

		try {
			$this->Disable();
		} catch (Interspire_Addons_Exception $e) {
			$this->db->RollbackTransaction();
			throw new Interspire_Addons_Exception($e->getMessage(), $e->getCode());
		}

		require dirname(__FILE__) . '/schema.' . SENDSTUDIO_DATABASE_TYPE . '.php';
		foreach ($tables as $tablename) {
			$query = 'DROP TABLE [|PREFIX|]' . $tablename . ' CASCADE';
			$result = $this->db->Query($query);
			if (!$result) {
				$this->db->RollbackTransaction();
				throw new Interspire_Addons_Exception("There was a problem running query " . $query . ": " . $this->db->GetErrorMsg(), Interspire_Addons_Exception::DatabaseError);
			}
		}

		foreach ($sequences as $sequencename) {
			$query = 'DROP SEQUENCE [|PREFIX|]' . $sequencename;
			$result = $this->db->Query($query);
			if (!$result) {
				$this->db->RollbackTransaction();
				throw new Interspire_Addons_Exception("There was a problem running query " . $query . ": " . $this->db->GetErrorMsg(), Interspire_Addons_Exception::DatabaseError);
			}
		}
		
		//unInstall files changes
		$this->uninstallAddonFiles('customheader');
        try {
			$status = parent::UnInstall();
		} catch (Interspire_Addons_Exception $e) {
			$this->db->RollbackTransaction();
			throw new Interspire_Addons_Exception($e->getMessage(), $e->getCode());
		}

		$this->db->CommitTransaction();

		return true;
	}
	
	/*
	AddNewLineInExisting
	*/
	public function installAddonFiles ($addon = "none"){
        $install_data_file_schema = IEM_ADDONS_PATH . "/{$addon}/modifier/modifier_points.php";
        if (! file_exists($install_data_file_schema)) {
            return true;
        } else {
            require_once $install_data_file_schema;
			$dataFilePath = IEM_ADDONS_PATH . "/{$addon}/modifier/install_data.php";
            $fhDPath = fopen($dataFilePath, 'r');
			$install_data_file_content = fread($fhDPath, filesize($dataFilePath));
			fclose($fhDPath);
			
            $errors = array();
            $adname = (isset($installer_AddonName) ? $installer_AddonName : "");
            if (isset($data_files) && is_array($data_files) && count($data_files) > 0) {
                $temp_path = IEM_ADDONS_PATH . "/{$addon}/modifier/existing/";
                if (is_writable($temp_path)) {
                    foreach ($data_files as $key => $data_file) {
					    $data_file_to_replace = $data_file['data_file'];
                        $temp_data_file = $temp_path . md5($data_file_to_replace) . substr($data_file_to_replace, - 4, 4);
                        if (is_writable($data_file_to_replace)) {
                            if (! file_exists($temp_data_file)) {
                                if (! copy($data_file_to_replace, $temp_data_file)) {
                                    $errors[] = "Error: {$temp_data_file} for {$data_file_to_replace}";
                                }
							}	
							$content = "";
							foreach ($data_file['data'] as $k => $lv) {
								$lv = $this->palace_info($lv);
								if (! $lv) {
									continue;
								}
								$line = $lv['line'] - 1;
								$line_log = $lv['line'];
								if($lv['insert'] == 'a'){
									$insert = "after";
								}elseif($lv['insert'] == 'i'){
									$insert = "inline";
								}elseif($lv['insert'] == 'r'){
									$insert = "replace";
								}elseif($lv['insert'] == 'lr'){
									$insert = "linereplace";
								}else{
									$insert = "before";
								}
								$contentType = 'array';
								$replaceType = 'default';
								
								if($insert == "linereplace"){
									$contentType = 'direct';
									$replaceType = 'replace';
									if($content == ""){
										$fh = fopen($data_file_to_replace, 'r');
										$content = fread($fh, filesize($data_file_to_replace));
										fclose($fh);
									}
									$addon_replacedatacontent = $this->insert_contentfile($lv['replacetext'], $install_data_file_content, $replaceType);
								}else{
									$contentType = 'array';
									if($content == ""){
										$content = file($data_file_to_replace, FILE_IGNORE_NEW_LINES);
									}
								}
								$addon_datacontent = $this->insert_contentfile($lv['content'], $install_data_file_content, $replaceType);
								
								if ($data_file['type'] == "tpl") {
									$suffix = "<!--";
									$postfix = "-->";
								} elseif ($data_file['type'] == "css") {
									$suffix = "/*";
									$postfix = "*/";
								} elseif ($data_file['type'] == "js") {
									$suffix = "/*";	
									$postfix = "*/";
								} else {
									$suffix = "/*";
									$postfix = "*/";
								}
								$finalsuffix = "{$suffix}Addon Main: START {$postfix}";
								$finalposfix = "{$suffix}Addon Main($adname), {$insert} : END {$postfix}";
								if ($data_file['reque']) {
									$_a = explode(PHP_EOL, $addon_datacontent);
									if (count($_a) < 2) {
										$_a = explode("\r", $addon_datacontent);
									}
								}
								$addon_datacontent = trim(($data_file['reque']) ? implode("", $_a) : $addon_datacontent);
								$addon_datacontent = "{$finalsuffix}{$addon_datacontent}{$finalposfix}";
								if ($insert == "after") {
									$content[$line] = rtrim($content[$line]) . PHP_EOL . $addon_datacontent;
								} elseif ($insert == "inline") {
									$content[$line] = rtrim($content[$line]) . $addon_datacontent;
								}elseif ($insert == "replace") {
									$content[$line] = $addon_datacontent."//OldData".rtrim($content[$line]);
								}elseif ($insert == "linereplace") {
									$content = str_replace(array(trim($addon_replacedatacontent)), array($addon_datacontent), $content, $bool);
								} else {
									$content[$line] = $addon_datacontent . PHP_EOL . $content[$line];
								}
							}
							$result = $this->contentSave($data_file_to_replace, $content, $contentType);
							if (! $result) {
								$errors[] = "ERROR: {$file_to_replace}";
							}
							
						} else {
                            $errors[] = "ERROR: " . realpath($data_file_to_replace) . " is not writable";
                        }
                    }
                } else {
                    $errors[] = "The folder( {$temp_path} ) is not writable";
                }
				
            }
            if (count($errors) > 0) {
                throw new Exception("ERROR: Unable to install addon ( {$adname} ): <br>" . implode("<br>", $errors));
            }
        }
        return true;
    }
	
	//Uninstall Addon file
    public function uninstallAddonFiles ($addon = "none"){
        $install_data_file = IEM_ADDONS_PATH . "/{$addon}/modifier/modifier_points.php";
        if (! file_exists($install_data_file)) {
            return true;
        } else {
            require_once $install_data_file;
            $errors = array();
            $adname = (isset($installer_AddonName) ? $installer_AddonName : "");
            if (isset($data_files) && is_array($data_files) && count($data_files) > 0) {
                $temp_path = IEM_ADDONS_PATH . "/{$addon}/modifier/existing/";
                if (is_writable($temp_path)) {
                    foreach ($data_files as $key => $data_file) {
                        $data_file_to_replace = $data_file['data_file'];
                        $temp_data_file = $temp_path . md5($data_file_to_replace) . substr($data_file_to_replace, - 4, 4);
                        if (is_writable($data_file_to_replace)) {
                            if (file_exists($temp_data_file)) {
                                if (! copy($temp_data_file, $data_file_to_replace)) {
                                    $errors[] = "ERROR: {$data_file_to_replace} with {$temp_data_file}";
                                } else {
                                    if (! unlink($temp_data_file)) {
                                        $errors[] = "ERROR: deleting temp data_file: {$temp_data_file} for {$data_file_to_replace}";
                                    }
                                }
                            }
                        } else {
                            $errors[] = "ERROR: {$data_file_to_replace} is not writable";
                        }
                    }
                } else {
                    $errors[] = "ERROR: ( {$temp_path} ) is not writable";
                }
            }
            if (count($errors) > 0) {
                throw new Exception("ERROR: Unable to uninstall addon ( {$adname} ): <br>" . implode("<br>", $errors));
            }
        }
        return true;
    }
	
	//place content in file
    public function insert_contentfile ($block, $data_content, $pattern="default"){
		if($pattern == "default"){
			$content_chk1 = md5(rand() . rand());
			$content_chk2 = md5(rand() . rand());
			$content_chk3 = md5(rand() . rand());
			$content_chk4 = md5(rand() . rand());
			$data_content = str_replace('(', $content_chk1, $data_content);
			$data_content = str_replace(')', $content_chk2, $data_content);
			$data_content = str_replace('?', $content_chk3, $data_content);
			$data_content = str_replace('.', $content_chk4, $data_content);
			$pattern = "/#COPY_BLOCK_{$block}#([^\.)]+)#FINISH_BLOCK_{$block}#/i";
			$rm = preg_match($pattern, $data_content, $match);
			$data_content = ($rm) ? $match[1] : "";
			$data_content = str_replace($content_chk1, '(', $data_content);
			$data_content = str_replace($content_chk2, ')', $data_content);
			$data_content = str_replace($content_chk3, '?', $data_content);
			$data_content = str_replace($content_chk4, '.', $data_content);
			return trim($data_content);
		}else{
			$contentStart = "#COPY_BLOCK_{$block}#";
			$contentEnd = "#FINISH_BLOCK_{$block}#";
			$positionStart = strpos($data_content, $contentStart);
			$positionEnd = strpos($data_content, $contentEnd);
			$totalChar = intval($positionEnd) - intval($positionStart);
			$data_content = substr($data_content, $positionStart, $totalChar);
			$data_content = str_replace($contentStart,"", $data_content);
			$data_content = str_replace($contentEnd,"", $data_content);
			return trim($data_content);
		}	
    }
	
	//Insert information
    public function palace_info ($data){
        if (is_string($data[0])) {
            foreach ($data as $k => $v) {
                $a = explode(";", $v);
                $d = array(
                'line' => $a[1] , 
                'insert' => $a[2] , 
                'content' => $a[3] ,
				'replacetext' => $a[4]);
                if ($this->enableDisable($a[0])) {
                    return $d;
                }
            }
            return false;
        } else {
            return $data;
        }
        return $data;
    }
	
	//check Addon enable or disable
    public function enableDisable ($s){
        $i = false;
        $a = explode(",", $s);
        $addon_system = new Interspire_Addons();
        foreach ($a as $k => $v) {
            if ($v == "default") {
                return true;
            }
            $i = $addon_system->isEnabled($v);
        }
        return $i;
    }
    
	//Addon content save in files
    public function contentSave ($data_file, $content = array(), $contentType = "array"){
        $result = fopen($data_file, "w+");
        if (! $result) {
            return $result;
        }
		if($contentType == "direct"){
			fwrite($result, $content);
			fclose($result);
			return true;
		}else{
			foreach ($content as $k => $v) {
				$result = @file_put_contents($data_file, rtrim($v) . PHP_EOL, FILE_APPEND);
			}
		}	
        return $result;
    }
	
    public function Enable (){
        try {
            $status = parent::Enable();
        } catch (Interspire_Addons_Exception $e) {
            throw new Interspire_Addons_Exception($e->getMessage(), $e->getCode());
        }
        return true;
    }

    public function Disable (){
        try {
            $status = parent::Disable();
        } catch (Interspire_Addons_Exception $e) {
            throw new Interspire_Addons_Exception($e->getMessage(), $e->getCode());
        }
        return true;
    }

    public function Admin_Action_Default (){
		
	}
	
	function GetEventListeners (){ 
		$my_file = "{%IEM_ADDONS_PATH%}/{$this->AddonName}/{$this->AddonName}.php";
        $listeners = array();
        $listeners[] = array('eventname' => 'IEM_USERAPI_GETPERMISSIONTYPES' , 'trigger_details' => array('Interspire_Addons' , 'GetAddonPermissions') , 'trigger_file' => $my_file);
        return $listeners;
	}

    static function RegisterAddonPermissions (){
		return true;
	}
	
	
	protected function GetOops ($oops = 'customheader'){
        $oops = (is_array($oops)) ? $oops[0] : $oops;
        $path = $this->addon_base_directory . $this->addon_id . '/oops/' . strtolower($oops) . '.php';
        if (! is_file($path)) {
            return false;
        }
        require_once $path;
        $class = $oops . '_API';
        $oops = new $class();
        $oops->template_system = $this->template_system;
        return $oops;
    }
}