<?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, Add_addon_installer_API

 */



/**

 * 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, Addons_add_addon_installer

 */

class Add_addon_installer_API extends API{

	//Database Construtor Object

    private $db;

    public function __construct (){

        $this->db = IEM::getDatabase();

    }

	

	//Installation addon

    public function install ($addon = "none"){

        $install_data_file_schema = IEM_ADDONS_PATH . "/{$addon}/config/config.schema.php";

        if (! file_exists($install_data_file_schema)) {

            $this->log($addon,array());

            return true;

        } else {

            require_once $install_data_file_schema;

            $install_data_file_content = @file(IEM_ADDONS_PATH . "/{$addon}/config/install_data.php", FILE_IGNORE_NEW_LINES);

            $install_data_file_content = (! $install_data_file_content) ? "" : implode('', $install_data_file_content);

            $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}/config/temp/";

                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 = file($data_file_to_replace, FILE_IGNORE_NEW_LINES);

                                foreach ($data_file['data'] as $k => $lv) {

                                    $lv = $this->insert_info($lv);

                                    if (! $lv) {

                                        continue;

                                    }

                                    $line = $lv['line'] - 1;

                                    $line_log = $lv['line'];

                                    $insert = ($lv['insert'] == 'a') ? "after" : (($lv['insert'] == "i") ? "inline" : "before");

                                    $addon_datacontent = $this->install_content($lv['content'], $install_data_file_content);

                                    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}Telesys Addon Main: START {$postfix}";

                                    $finalposfix = "{$suffix}Telesys 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;

                                    } else {

                                        $content[$line] = $addon_datacontent . PHP_EOL . $content[$line];

                                    }

                                }

                                $result = $this->save($data_file_to_replace, $content);

                                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";

                }

            }

            $this->log($addon,$errors);

            if (count($errors) > 0) {

                throw new Exception("ERROR: Unable to install addon ( {$adname} ): <br>" . implode("<br>", $errors));

            }

        }

        return true;

    }

	

	//LOG EVENT

    private function log ($addon,$errors){

        return true;

    }



	//Insert information

    public function insert_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]);

                if ($this->addon_condition($a[0])) {

                    return $d;

                }

            }

            return false;

        } else {

            return $data;

        }

        return $data;

    }



	//Addon condition

    public function addon_condition ($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 SAVE files

    public function save ($data_file, $content = array()){

        $result = fopen($data_file, "w+");

        if (! $result) {

            return $result;

        }

        foreach ($content as $k => $v) {

            $result = @file_put_contents($data_file, rtrim($v) . PHP_EOL, FILE_APPEND);

        }

        return $result;

    }



	//Put Content

    public function install_content ($block, $data_content){

        $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);

    }



	//Uninstall Addon

    public function uninstall ($addon = "none"){

        $install_data_file = IEM_ADDONS_PATH . "/{$addon}/config/config.schema.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}/config/temp/";

                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;

    }

}