<?php

require_once 'include/upload_file.php';
require_once 'include/utils/sugar_file_utils.php';

/**
 *
 * Wrap profile restricted functions for SugarCRM PRO/ENT/ULT and OnDemand
 *
 */
if (!class_exists('FunctionWrapper')) {

    class FunctionWrapper {
        /**
         * Sets the value of a configuration option
         * string ini_set ( string $varname , string $newvalue )
         */
        static function _ini_set($varname, $newvalue) {
            // Not implemented beacuse of no alternatives
        }

        /**
         * Call a callback with an array of parameters
         * mixed call_user_func_array ( callable $callback , array $param_arr )
         */
        static function _call_user_func_array($function, array $params) {
            // array_intersect implementation
            if($function == "array_intersect") {
                $filterArray = $params;
                $result = array_shift($filterArray);
                foreach($filterArray as $filter){
                    $result = array_intersect($result, $filter);
                }

                return $result;
            }
        }

        /**
         * Deletes a file
         * bool unlink ( string $filename [, resource $context ] )
         */
        static function _unlink($filename)
        {
            // Not implemented because of no alternatives
            // if(class_exists('UploadStream')) {
            //    $uploadStream = new UploadStream();
            //    $uploadStream->unlink($filename);
            // }
        }
        
        /**
         * Reads entire file into an array
         * array file ( string $filename [, int $flags = 0 [, resource $context ]] )
         */
        static function _file($filename) {
            $uploadFile = new UploadFile();
            // Remove upload:// from file path string
            $uploadFile->temp_file_location = str_replace('upload://', '', $uploadFile->get_upload_path($filename));
            $fileString = $uploadFile->get_file_contents();
            return explode("\n", $fileString);
        }

        /**
         * Checks whether a file or directory exists
         * bool file_exists ( string $filename )
         */
        static function _file_exists($filename) {
            // If method doesn't exist for static class return true
            if(!method_exists('SugarAutoloader', 'fileExists')) {
                // Try to check if $filename is file (for SugarCRM 6.5 PRO/ENT version)
                return self::_is_file($filename);
            }

            // Dirty fix, to add filename to excluded (white listed) files
            SugarAutoLoader::$exclude[] = $filename;
            return SugarAutoloader::fileExists($filename);
        }

        /*
         * Reads entire file into a string
         * string file_get_contents ( string $filename [, bool $use_include_path = false [, resource $context [, int $offset = 0 [, int $maxlen ]]]] )
         */
        static function _file_get_contents($filename){
            $uploadFile = new UploadFile();
            $uploadFile->temp_file_location = $filename;
            return $uploadFile->get_file_contents();
        }

        /*
         * Write a string to a file
         * int file_put_contents ( string $filename , mixed $data [, int $flags = 0 [, resource $context ]] )
         */
        static function _file_put_contents($filename, $data)
        {
            $pcsv = null;

            if(class_exists('SidecarDropMetaDataUpgrader') && class_exists('SidecarMetaDataUpgrader')) {
                 $fileHack = new SidecarDropMetaDataUpgrader(new SidecarMetaDataUpgrader(), array());
                 $fileSize = $fileHack->save($filename, $data);
                 return true;
            }

            // Not implemented beacuse of no alternatives
            if(self::_file_exists("include/parsecsv.lib.php")) {
                include_once "include/parsecsv.lib.php";
                $pcsv = new parseCSV(null, null, null, array());
            } else {
                // Try to load file in different path
                if(self::_file_exists("vendor/parsecsv/php-parsecsv/parsecsv.lib.php")) {
                    include_once "modules/AnalyticReporting/polyfills/PCSV.php";

                    $pcsv = new PCSV(null, null, null, array());
                }
            }

            // Fixed issue, when parseCSV initialization is trying to count() $conditions parameter which was null
            return $pcsv->_wfile($filename, $data);
        }

        /*
         * Moves an uploaded file to a new location
         * bool move_uploaded_file ( string $filename , string $destination )
         */
        static function _move_uploaded_file($filename, $destination){
            return UploadFile::move_uploaded_file($filename, $destination);
        }

        /**
         * Check if directory exists
         *
         * @param $dirname
         * @return bool
         */
        static function _is_dir($dirname)
        {
            // Not implemented because of no alternatives
        }

        /*
         * Tells whether the filename is a regular file
         * bool is_file ( string $filename )
         */
        static function _is_file($filename) {
            return sugar_is_file($filename);
        }

        /*
         * Limits the maximum execution time
         * bool set_time_limit ( int $seconds )
         */
        static function _set_time_limit($value) {
            // Not implemented beacuse of no alternatives
        }

        /*
         * Changes file mode
         * bool chmod ( string $filename , int $mode )
         */
        static function _chmod($fileName, $mode) {
            // Not implemented because of no alternatives
        }

        /**
         * Create directory
         *
         * @param $filename
         * @param $mode
         * @param $recursive
         * @return void
         */
        static function _mkdir($filename, $mode, $recursive)
        {
            // Not implemented because of no alternatives
        }

        /**
         * Copy files
         *
         * @param $source
         * @param $target
         * @return void
         */
        static function _copy($source, $target)
        {
            // Not implemented because of no alternatives
        }

        /*
        * No alternative way to call function dynamically, call statically instead.
        * mixed _call_bean_function ( Object $bean , string $function )
        */
        static function _call_bean_function($bean, $function) {
            switch ($function) {
                case 'getCurrencies':
                    return $bean->getCurrencies();
                case 'getCommitStageDropdown':
                    return $bean->getCommitStageDropdown();
                case 'getOutboundEmailDropdown':
                    return $bean->getOutboundEmailDropdown();
            }
        }

        /**
         * Creates a file with a unique filename, with access permission set to 0600, in the specified directory.
         *
         * @param $dir
         * @param $prefix
         *
         * @return string
         */
        static function _tempnam($dir, $prefix) {
            $name = (string) str_replace(".", "", $prefix . getmypid() . microtime(true));
            $path = $dir .'/' . $name;
            if (self::_file_exists($path)) {
                return self::_tempnam($dir, $prefix);
            } else {
                return $path;
            }
        }

        /**
         * @param string $moduleName
         * @return object
         *
         * Get module instance (bean)
         */
        static function _getBean($moduleName) {
            return BeanFactory::getBean($moduleName);
        }

        /**
         * @param string $moduleName
         * @return object
         *
         * Get module instance (bean)
         */
        static function _newBean($moduleName) {
            return BeanFactory::newBean($moduleName);
        }

        static function _simplexml_load_string($xml) {
            $xmlReader = new XMLReader;
            $xmlReader->xml($xml);
            $doc = new DOMDocument;
            while ($xmlReader->read() && $xmlReader->name !== 'ARImportData');
            return @simplexml_import_dom($doc->importNode($xmlReader->expand(), true));
        }

        static public function save($filename, $data)
        {
            if(self::_file_exists("include/parsecsv.lib.php")) {
                include_once "include/parsecsv.lib.php";
            } else {
                // Try to load file in different path
                if(self::_file_exists("vendor/parsecsv/php-parsecsv/parsecsv.lib.php")) {
                    include_once "vendor/parsecsv/php-parsecsv/parsecsv.lib.php";
                }
            }

            $pcsv = new parseCSV();
            $pcsv->save($filename, $data);
        }
    }

}