<?php
require_once(EIFR_ROOT . 'libraries/file.php');
require_once(EIFR_ROOT . 'libraries/httpdown.php');

class GetResource {
    /**
     * get Relative Application Root Path
     * Example: if path="/eifr/linkfiles" and DIR_INSTALL="/eifr" then return "/linkfiles"
     */
    function getRelativeAppRootPath($path = '') {
        return substr(CFile::removeLastSlash($path), strlen(CFile::removeLastSlash(DIR_INSTALL)));
    }
    
    /**
     * 
     * @param String $str : content
     * @param String $imgUrl : path to files relative to the document root(system root).
     */
    function getContent($str, $imgUrl = '') {
        // Path to files relative to the document root(system root).
        $def_webdir = DIR_INSTALL . 'linkfiles/image/' . CFile::genDatePath(); 
        // specify the absolute path for the files directory.
        // Examples: if windows then 'C:\\MySite\\userfiles\\'; if linux then '/root/mysite/userfiles/'.
        $base_filedir = CFile::removeLastSlash(EIFR_ROOT);

        if ($imgUrl == '') {
            $imgUrl = $def_webdir;
        } 
        $imgDir = $base_filedir . $this -> getRelativeAppRootPath($imgUrl);; 
        // create folder
        $rtn_cf = CFile :: createServerFolder($imgDir);

        $imgUrl .= '/';
        $imgDir .= '/';

        $clHttpDown = new HttpDown();

        $basehost = "http://" . $_SERVER["HTTP_HOST"];

        $str = str_replace(strtolower($basehost), "", $str);
        $str = str_replace(strtoupper($basehost), "", $str);

        $img_array = array();
        preg_match_all("/(src|SRC)=[\"|'| ]{0,}(http:\/\/(.*)\.(gif|jpg|jpeg|bmp|png))/isU", $str, $img_array);
        $img_array = array_unique($img_array[2]);

        $nowtime = time(); 
        $rndnum = rand(10000, 99999);
        // save file  and replace string
        foreach($img_array as $key => $value) {
            if (@eregi($basehost, $value)) continue;
            if (SYS_WEBURL != $basehost && @eregi(SYS_WEBURL, $value)) continue;
            if (!@eregi("^http://", $value)) continue;

            $clHttpDown -> OpenUrl($value);
            $itype = $clHttpDown -> GetHead("content-type");
            if ($itype == "image/gif") $itype = ".gif";
            else if ($itype == "image/png") $itype = ".png";
            else $itype = ".jpg";
            $value = trim($value); 
            // file rename
            $rndFileName = $imgDir . $nowtime . '_' . $rndnum . $key . $itype;
            $fileurl = $imgUrl . $nowtime . '_' . $rndnum . $key . $itype; 
            // down and save file
            $rs = $clHttpDown -> SaveToBin($rndFileName);
            if ($rs) {
                $str = str_replace($value, $fileurl, $str);
            } 
        } 
        $clHttpDown -> Close();

        return $str;
    } 
} 

?>
