<?php
/*------------------------------------------------------------------------------+
 	<meta http-equiv="Content-Type" content="text/php; charset=utf-8">
	
   text2html てきでこ Akio Tenman. <http://text2html.sourceforge.jp/>
   Copyright (C) 2008 Akio Tenman <tenman@users.sourceforge.jp>

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 +------------------------------------------------------------------------------*/
 //このアプリで、外部API等を参照する場合、allow_url_fopenはtrueである必要があります。

    mb_language( 'Japanese' );
	
    if(preg_match("/^[A-z]:.+/",__FILE__)){
    	$separater = '\\';
    }else{
    	$separater = '/';
    }
	
	if(!isset($text2html_url)){
		$text2html_url = "http://". $_SERVER['HTTP_HOST'] . dirname($_SERVER['PHP_SELF']).$separater;
    }

	if(!isset($text2html_dir_path)){
		$text2html_dir_path = dirname(dirname(__FILE__)).$separater;
    }

    if(!isset($cache)){
    $cache = true;

    }
//スクリプトディレクトリ

    define("TEXTTOHTML_SCRIPTS_DIR_PATH",$text2html_dir_path."scripts{$separater}");

//主に、htmlパターン用のストック
    define("TEXTTOHTML_DATA_DIR_PATH", $text2html_dir_path ."data{$separater}");
    define("TEXTTOHTML_CHANGE_TXT",TEXTTOHTML_DATA_DIR_PATH."change.txt");
    define("CHANGE_PATTERN_PATH",TEXTTOHTML_DATA_DIR_PATH."change.xml");

//画像保管用ディレクトリ
    define("TEXTTOHTML_IMAGE_DIR_PATH", $text2html_dir_path."images{$separater}");
    define("TEXTTOHTML_IMAGE_DIR_URL", $text2html_url."images{$separater}");
//イメージコピー用スクリプト
    define("TEXTTOHTML_COPY_IMG_WIDTH","100");
    define("IMAGE_IMPORT_PATH", $text2html_dir_path."import{$separater}");
    define("IMAGE_IMPORT_SVR", $text2html_url."import{$separater}image.php");
//source true
    define("TEXTTOHTML_CODE_WRAP_WIDTH",48);
//画像コピーディレクトリ
    define("TEXTTOHTML_IMPORT_DIR_PATH","import{$separater}");

    //トラックバックフォーム　WEBサービス
    //define("TEXTTOHTML_TRACKBACK_URL","");

//キャッシュディレクトリ

    define("CACHE_LITE_PATH","Cache{$separater}Lite.php");
    define("CACHE_DIR_PATH",$text2html_dir_path."cache{$separater}");
    define("CACHE_LIFE_TIME",3600);
    define("CACHE_SWITCH",$cache); //falseキャッシュの破棄

//設定ファイル
    define("HTML_RULE_CONFIG_FILE_PATH",TEXTTOHTML_SCRIPTS_DIR_PATH."html.ini");
    define("TEXTTOHTML_FONT_DIR_PATH",$text2html_dir_path."font{$separater}");
    define("TEXTTOHTML_FONTS_PATH",TEXTTOHTML_FONT_DIR_PATH."fonts.inc");

//MEMO
/*----------------------------------------------------------------------+
 * get_querys()で使用する配列の説明。

  "tenki"=>array(
        'charset'=>'UTF-8',
        'type'=>'contents',
        'url'=>'http://www.odekake.biz/branch/?date=+++E_KEYWORD+++',
        "response"=>"+++CONTENTS+++\n"),

    ['type']
    contents_rebuild

                関数による処理を行ったうえでコンテンツとする。
    url　function
                クラス外部のメソッド
                必須
    contents
                単純なレスポンスをコンテンツとする　URL必須
    link
                a img用のURLとして
------------------------------------------------------------------------*/

class trans{

    var $document;
    var $source;
    var $html;
    var $header;
    var $header_info = array();
    var $midasilist;
    var $footNote = array();
    var $footNoteList;
    var $content_no_h1;
    var $content_no_h2;
    var $content_no_h3;
    var $content_no_h4;
    var $content_no_h5;
    var $content_no_h6;

    var $separator;
    var $element;
    var $wm;
    var $content;
    var $attr;
    var $content_attr;
    var $description;
	var $copy_target;
	var $copy_uri;


    function trans($document){ 

		$document = str_replace(array("\r"),"\n",$document);
		$document = $this->tag_br($document);
		$this->document = $this->tag_clear($document);
    }

    function delete_break($matches){
        $result = "";
		
		foreach($matches as $key=>$match){
			if($key==0){
				$result .= str_replace("\n","",$match);
			}
		}
		
		$result = preg_replace("/\s{2,}/"," ",$result);
		
		return $result;
    }

    function tag_br($text){
		$text = str_replace("\r","",$text);
		$text = preg_replace("/\s=/","=",$text);
		$text = preg_replace_callback("/[^(code:)](<[^>]+\s{2,}[^>]+>)/usi",array($this, 'delete_break'),$text);

		return $text;

    }

     function get_querys($text){

		if(ini_get("allow_url_fopen") == false){
	
		return $text;
		}

 //重複名の誤変換を避けるために、文字数の長い順にソート
$get_querys = array(
/*キー名は10文字未満*/
    "googlemaps"=>array(
        'charset'=>'UTF-8',
        'type'=>'link',
        'response'=>"<sup class=\"gmaps\"><a href=\"http://www.google.co.jp/maps?f=q&amp;hl=ja&amp;oe=UTF8&amp;ie=UTF8&amp;q=+++E_KEYWORD+++\" title=\"[ +++KEYWORD+++ 地図リンク]\">Map</a></sup>"),

    "qrcode"=>array(
        'charset'=>'SHIFT_JIS',
        'type'=>'link',
        "response"=>"<img src=\"http://www.odekake.biz/images/qr/qr_img.php?s=3&amp;v=0&amp;e=m&amp;d=+++E_KEYWORD+++\" alt=\"+++KEYWORD+++\" width=\"87\" height=\"87\" />"),

    "goo_search"=>array(
        'charset'=>'UTF-8',
        'type'=>'link',
        "response"=>"<a href=\"http://search.goo.ne.jp/web.jsp?PT=bb_tp&amp;from=query&amp;MT=+++E_KEYWORD+++&amp;web.x=54&amp;web.y=13&amp;DC=10\">goo検索+++KEYWORD+++</a>"),

    "pdf"=>array(
        'charset'=>'UTF-8',
        'type'=>'link',
        "response"=>"<a href=\"http://html2pdf.biz/api?url=+++E_KEYWORD+++&amp;ret=pdf\">+++KEYWORD+++PDF</a>"),

    "円グラフ"=>array(
        'charset'=>'UTF-8',
        'type'=>'query',
        "response"=>"<img src=\"http://graph.heartrails.com/api/?+++E_KEYWORD+++\" alt=\"+++KEYWORD+++\"  />\n"),
   "郵便番号"=>array(
        'charset'=>'UTF-8',
        'type'=>'contents_rebuild',
        'function'=>'postal_code',
        'url'=>'http://zip.cgis.biz/xml/zip.php?zn=+++E_KEYWORD+++',
        "response"=>"+++CONTENTS+++"),
    "wikipedia"=>array(
        'charset'=>'UTF-8',
        'type'=>'contents_rebuild',
        'function'=>'simpleapi_wikipedia',
        'url'=>'http://wikipedia.simpleapi.net/api?keyword=+++E_KEYWORD+++&output=php',
        "response"=>"+++CONTENTS+++"),

"tenki"=>array(
        'charset'=>'UTF-8',
        'type'=>'contents',
        'url'=>'http://www.odekake.biz/branch/?date=+++E_KEYWORD+++',
        "response"=>"+++CONTENTS+++\n"),
    );
	
 uksort($get_querys,"text2html_cmp");

 if(isset($get_querys)){
    foreach($get_querys as $key=>$val){
        if(preg_match_all("/($key>\()([^\)]+)(\))/u", $text, $matches, PREG_SET_ORDER)){
		
            foreach($matches as $key=>$match){
			
                $cache = use_cache($matches[$key][0]);
                if($cache[0]){
				
                    $text 	= str_replace($matches[$key][0],$cache[1],$text)."\n";
                }else{
				
                    $enc 	= mb_convert_encoding($match[2],$val['charset'],"auto");
                    $no_enc = mb_convert_encoding($match[2],"UTF-8","auto");
                    $no_enc = str_replace("\n","",$no_enc);

                    switch($val['type']){

                    case('link'):

                        $enc 		 = urlencode($enc);
                        $replacement = mb_convert_encoding($val['response'],"UTF-8","auto");
                        $replacement = str_replace(array("+++E_KEYWORD+++","+++KEYWORD+++"),array($enc,$no_enc),$val['response']);
                        $replacement = trim($replacement);
                    break;

                    case('contents'):

                        $enc 		= urlencode($enc);
                        $target 	= mb_convert_encoding($val['url'],"UTF-8","auto");
                        $target 	= str_replace(array("+++E_KEYWORD+++","+++KEYWORD+++"),array($enc,$no_enc),$target);
                        $host 		= parse_url($target);
                        $host 		= $host['host'];
						
                            try{

                                if(!$fp = fsockopen ($host, 80, $errno, $errstr, 5)){
								
                                throw new Exception('を、取得できません。サービスを停止してるかどうか確認してください。');
                                }
								
                                socket_set_timeout($fp, 3);
                                fputs ($fp, "GET / HTTP/1.0\r\nHost: ".$_SERVER['HTTP_HOST']."\r\n\r\n");
                                $replacement 	= mb_convert_encoding(file_get_contents($target),"UTF-8","auto");
                                $stat 			= socket_get_status($fp);
								
                                if ($stat["timed_out"]) {

                                throw new Exception('タイムアウトしました。');
                                }

                                fclose($fp);

                            }catch (Exception $e) {
							
                            $errstr = mb_convert_encoding($errstr,"UTF-8","auto");
 echo '<div style="text-align:left;padding:2em;background:#FF99FF;">例外: ',$target,$e->getMessage(), "\n</div>\n";
                            }

                    break;
					
                    case('query'):

                        $replacement 	= mb_convert_encoding($val['response'],"UTF-8","auto");
                        $querys 		= explode("&",$enc);
                        $enc 			= "";
						
							foreach($querys as $query){
	
								preg_match("/([^=]+)(=)(.+)/", $query, $hit);
		
									if($hit){
										$enc .= '&amp;'.urlencode($hit[1]).$hit[2].urlencode($hit[3]);
									}
	
							}

                        $enc 			= str_replace("\n","",$enc);
                        $no_enc 		= "";
                        $replacement 	= str_replace(array("+++E_KEYWORD+++","+++KEYWORD+++"),array($enc,$no_enc),$val['response']);

                    break;

                    case('contents_rebuild'):

                        $enc 		 = urlencode($enc);
                        $replacement = mb_convert_encoding($val['response'],"UTF-8","auto");
                        $target 	 = str_replace(array("+++E_KEYWORD+++","+++KEYWORD+++"),array($enc,$no_enc),$val['url']);

                        $host 		 = parse_url($target);
                        $host  		 = $host['host'];
						
                            try{

                                if(!$fp = fsockopen ($host, 80, $errno, $errstr, 5)){
								
                                throw new Exception('を、取得できません。サービスを停止してるかどうか確認してください。');
                                }
								
                                socket_set_timeout($fp, 3);
                                fputs ($fp, "GET / HTTP/1.0\r\nHost: ".$_SERVER['HTTP_HOST']."\r\n\r\n");

                                $replacement 	= mb_convert_encoding(@file_get_contents($target),"UTF-8","auto");
                                $function_name 	= $val['function'];
                                $replacement 	= $function_name($replacement);

                                $stat = socket_get_status($fp);
								
									if ($stat["timed_out"]) {
	
										throw new Exception('タイムアウトしました。');
									}

                                fclose($fp);


                            }catch (Exception $e) {
							
                            	$errstr = mb_convert_encoding($errstr,"UTF-8","auto");
 echo '<div style="text-align:left;padding:2em;background:#FF99FF;">例外: ',$target,$e->getMessage(), "\n</div>\n";
                            }
                    break;

                    }
					
            save_cache($matches[$key][0],$replacement);

            $text = str_replace($matches[$key][0],$replacement,$text)."\n";
                }

            }

        }

      }
    }
return $text;
}

    function number(){
        static $int = 0;

        $int++;
        return $int;
    }

    function text2html(){
	
        global $benchmark;
        global $source;
		global $content_name;
		
        $pear_file  = "";
        $timer      = false;
		$buffer 	= $this->document;
        $output_enc = "UTF-8";
		
        if(isset($benchmark) and $benchmark == true){
            include_once ("Benchmark/Timer.php");
            $timer = true;
            $oTimer =& new Benchmark_Timer();
            $oTimer->start ();
        }

            if($timer){ $oTimer->setMarker( 'preset' );}

        $buffer = $this->change_word($buffer);

            if($timer){ $oTimer->setMarker( 'change_word' );}
//table
        $buffer   = $this->text2html_table($buffer,"\n","table","tr:","tr","","","table");

            if($timer){ $oTimer->setMarker( 'text2html_table' );}
//blockquote
        $buffer   = $this->text2html_code($buffer,"\n","pre",'code:','code','','class="source"','souce');
		
            if($timer){ $oTimer->setMarker( 'text2html_code' );}
//heading
        $buffer   = $this->text2html_element($buffer,"\n","h6",'\*\*\*\*\*','a','', 'href="#TOP"','h6');
            if($timer){$oTimer->setMarker( 'elementh6' );}

        $buffer   = $this->text2html_element($buffer,"\n","h5",'\*\*\*\*','a','', 'href="#TOP"','h5');
            if($timer){ $oTimer->setMarker( 'elementh5' );}

        $buffer   = $this->text2html_element($buffer,"\n","h4",'\*\*\*','a','', 'href="#TOP"','h4');
            if($timer){$oTimer->setMarker( 'elementh4' );}

        $buffer   = $this->text2html_element($buffer,"\n","h3",'\*\*','a','', 'href="#TOP"','h3');
            if($timer){ $oTimer->setMarker( 'elementh3' );}

        $buffer   = $this->text2html_element($buffer,"\n","h2",'\*','a','', 'href="#TOP"','h2');
            if($timer){ $oTimer->setMarker( 'elementh2' );}

        $buffer   = $this->link_title($buffer);
            if($timer){ $oTimer->setMarker( 'link_title' );}

//vertical align
        $buffer   = $this->text2html_element($buffer,"\n","div",'==','p','', 'style="text-align:right;"','right');
            if($timer){$oTimer->setMarker( 'align:right' );}

        $buffer   = $this->text2html_element($buffer,"\n","div",'=','p','', 'style="text-align:center;"','center');
            if($timer){$oTimer->setMarker( 'align:center' );}

        $buffer = $this->note($buffer,"\n");
            if($timer){$oTimer->setMarker( 'note' );}

//見出しリスト
        asort($this->header_info);
        $this->midasilist = "<a name=\"TOP\" id=\"TOP\" >head line</a>\n";
        $kihou = "";
		
        foreach($this->header_info as $key=>$link){

            $kihou = str_repeat ('+', $link[1]-1);
            $this->midasilist .= "$kihou<span><a href=\"#$link[2]\">$link[3]</a></span>\n";
        }
            $this->midasilist = $this->text2html_list(trim($this->midasilist)."\n","\n","ol",'+','li','','','head-line');

//閉じタグチェック
            preg_match_all("/(<ol><li>)/u",$this->midasilist,$start,PREG_SET_ORDER);
            preg_match_all("/(<\/ol><\/li>)/u",$this->midasilist,$end,PREG_SET_ORDER);

            $rep = count($end)-count($start);

            switch(true){
            case(count($end) == count($start)):

            break;

            case(count($end) > count($start)):
				//閉じタグが多い
				$rep = $rep;
				$rep = str_repeat("<\/ol><\/li>",$rep + 1);
				$this->midasilist = preg_replace("/$rep<\/ol>$/m","</ol>",$this->midasilist);

            break;

            case(count($end) < count($start)):
				//閉じタグが少ない
				$rep = str_repeat('</ol></li>',abs($rep)-1);
	            $this->midasilist = preg_replace("/<\/ol>$/m","",$this->midasilist).$rep."</ol>";

            break;
            }

            $buffer = str_replace("[head_line]", $this->midasilist, $buffer);
            if($timer){$oTimer->setMarker( 'head_line' );}

//foot note

        foreach($this->footNote as $note){
            $this->footNoteList .= "<li><p><a href=\"#$note[1]\" name=\"$note[2]\" id=\"$note[2]\" >[".$note[0]."]</a>$note[3]</p></li>";
        }

        $this->footNoteList = "<ul class=\"foot-note-$content_name\">".$this->footNoteList."</ul>";
        $buffer = str_replace("[foot_note]",$this->footNoteList, $buffer);

//etc
            if($timer){$oTimer->setMarker( 'foot_note' );}

        $buffer = $this->keyword_change($buffer,"\n");
            if($timer){$oTimer->setMarker( 'keyword_change' );}
			
        $buffer = $this->read_php($buffer,"\n");
            if($timer){$oTimer->setMarker( 'read_php' );}

        $buffer = $this->keyword_change_inline($buffer,"\n");//ok
            if($timer){$oTimer->setMarker( 'keyword_change_inline' );}

        $buffer = $this->inline_tag($buffer);
            if($timer){$oTimer->setMarker( 'inline_tag' );}

        $buffer = $this->ruby($buffer);//これは、IE　xthml1.1
            if($timer){$oTimer->setMarker( 'inline_tag' );}

        $buffer = $this->trackback($buffer,"\n");
            if($timer){$oTimer->setMarker( 'trackback' );}

        $buffer = $this->maillink($buffer,"\n");
            if($timer){$oTimer->setMarker( 'maillink' );}

        $buffer = $this->youtube($buffer,"\n");
            if($timer){$oTimer->setMarker( 'youtube' );}

        $buffer = $this->txt2img($buffer,"\n");
            if($timer){$oTimer->setMarker( 'text2image' );}

        $buffer = $this->sound($buffer,"\n");
            if($timer){$oTimer->setMarker( 'text2image' );}

        $buffer = $this->foma_movie($buffer,"\n");
            if($timer){$oTimer->setMarker( '3gp' );}

        $buffer = $this->swf($buffer,"\n");
            if($timer){$oTimer->setMarker( '3gp' );}

        $buffer = $this->encode_query($buffer,"\n");
            if($timer){$oTimer->setMarker( 'encode_query' );}

        $buffer = $this->img_copy($buffer,"\n");
            if($timer){$oTimer->setMarker( 'img_copy' );}

        $buffer = $this->image($buffer,"\n");
            if($timer){$oTimer->setMarker( 'image' );}

        $buffer = $this->clear_both($buffer,"\n");
            if($timer){$oTimer->setMarker( 'clear_both' );}
			
        $buffer = $this->get_querys($buffer,"\n");
            if($timer){$oTimer->setMarker( 'get_querys' );}

        $buffer = $this->text2html_list($buffer,"\n","ul","\-",'li','','','unorder');
        $buffer = $this->text2html_list($buffer,"\n","ol",'+','li','','','order');
        $buffer = $this->text2html_list($buffer,"\n","ul",'※','li','style="font:size:70%;color:#66f;"',"style=\"list-style-type:none;\"","caution");
            if($timer){$oTimer->setMarker( 'list' );}

		//$buffer = $this->text2html_list2($buffer,"\n","blockquote",'引用:','p','','','quote');
        //入れ子可
        $buffer = $this->text2html_list($buffer,"\n","blockquote",'>','p','','','quote');
            if($timer){$oTimer->setMarker( 'list_blockquote' );}

        $buffer = $this->paragraf($buffer,"\n\n");
            if($timer){$oTimer->setMarker( 'paragraph' );}

        $buffer = $this->repair_end($buffer,"\n");
            if($timer){$oTimer->setMarker( 'repair_end' );}

        $text   = $this->result_encoding($buffer,"\n");
            if($timer){$oTimer->setMarker( 'result_encoding' );}

        if(isset($source) and $source == true){
		
            $source = $this->my_wordwrap($text);
            $source = str_replace("&#47;",'/',$source);

            $this->source   = '<div class="source_view">'.
            $this->style_set($source)."\n</div>";
        }else{
		
            $this->source   = "";
        }
            if($timer){$oTimer->setMarker( 'create_source' );}

        if($timer){
                $oTimer->setMarker( 'end' );
                $oTimer->stop ();
                ob_start();
                $oTimer->display ();
                $profile = ob_get_contents();
                ob_end_clean();

                return $text.$profile;
        }
         return $text;
    }

    function change_word($text){

		if(!defined('TEXTTOHTML_CHANGE_TXT')){return $text;}
		$file = TEXTTOHTML_CHANGE_TXT;

            if(file_exists($file)){
			
                $chenge_words = file($file);

                foreach($chenge_words as $chenge_word){
				
                	$chenge_word = mb_convert_encoding($chenge_word, "UTF-8","auto");

                    if(strstr($chenge_word,"#")){
                      list($before, $after) = explode("#", $chenge_word);
                      $text = str_replace($before , trim($after), $text);
                    }
                }

                return $text;
            }else{
			
                return $text;
            }

    }


function text2html_list($document = "", $separator = "\n",$element = "ul",$wm = '-',$content = 'li',$attr = '',$content_attr = '',$description = ''){

    $lines          = explode($separator,$document);
    $running        = false;
    $result         = '';
    $add_front      = '';
    $add_tail       = '';
    $add_end        = '';
    $end            ='';
    $tag_before     = "";
    $tag_after      = "";
    $body           = "";
    $content_no     = 1;
    $running        = false;
    $last_line      = false;
    $start_line     = false;
    $next_flag      = false;
    $diff_prev      = 0;
    $diff_next      = 0;
    $diff_count     = 0;
    $marker_length  = 0;
    $counter        = "";

    global $content_name;

     if(!empty($content_name) and !empty($description)){
        $description    = $description.'-'.$content_name;
     }else{
        $description    = $description.$content_name;
     }

    $start_element_set  = "<$element><$content>";
    $end_element_set    = "</$element></$content>";
    $start              = true;

foreach($lines as $key=>$line){

    $line               = $line."\n";
    if($current_flag    = preg_match("/^([$wm]+)(.+)/u",$line,$current)){

	    $marker_length  = @strlen($current[1]);


            //リスト変換のオンオフ判定

            if($marker_length > 0){$running =true;}else{$running = false;}


            //前後する行との関係をマーカー数を数えて判定。

            if($key > 0 ){

                $prev_flag  = preg_match("/^([$wm]+)(.+)/u",$lines[$key - 1],$prev);

                if(isset($prev[1])){

                    $prev_length    = strlen($prev[1]);
                    $diff_prev      = $marker_length - $prev_length ;
                }

            }else{

                $prev_flag = false;
            }


            if($running and !$next_flag){

                $last_line = true;
            }


            if(isset($lines[$key + 1])){

                $next_flag      = preg_match("/^([$wm]+)(.+)/u",$lines[$key + 1],$next);
                $next_length    = @strlen($next[1]);
                $diff           = $marker_length - $next_length;
                $diff_count     = $marker_length - 1;

            }
            if(isset($lines[$key + 2])){

                $diff_next      = $marker_length - $next_length;

            }
            if(!empty($attr)){
                $attr           = ' '.$attr;
            }

            if(!empty($content_attr)){
                $content_attr   = ' '.$content_attr;
            }

            switch($running and !$prev_flag){

                case(true):

                $id_name = ' '."id=\"$element-$description-".trim($content_no)."\"";

                if($diff_next > 0 or $marker_length > 1){

                    $start = str_repeat($start_element_set,abs($marker_length - 1 ))."<$element>";

                            $content_no++;
                }else{

                    $start = "<$element>";

                            $content_no++;
                }


                break;

                case(false):
                    $start = "";

                break;

            }


            switch($running and $key < count($lines) - 1 ){

                case(true):

                    //前行とのマーカーの差

                    switch(true){

                        case($diff_prev > 0):
                    //下位

                        $tag_before = str_repeat($start_element_set,abs($diff_prev));
                        $diff_count = $diff_count + $diff_prev;
                        $start = "";
                        break;

                        case($diff_prev < 0):

                    //上位

                        $tag_before = "<$content>";
                        $diff_count = $diff_count + $diff_prev;

                        break;
                        case($diff_prev == 0):

                    //同位

                        $tag_before = "<$content>";

                        break;

                        case(false):

                        $tag_before = "<$content>";

                        break;

                    }

                    //次行とのマーカーの差

                    switch(true){
                        case($diff_next > 0):

                    //上位

                        $tag_after =  "</$content>";

                        $repeat     = abs($diff_next);
                        $tag_after .= str_repeat($end_element_set,$repeat);

                        if($next_flag !== 1){

                        $repeat     = abs($diff_next) - 1;

                        $tag_after  =  "</$content>";
                        $tag_after .= str_repeat($end_element_set,$repeat);
                        $tag_after .= "</$element>";

                        }

                        if(empty($tag_after)){
                            $tag_after = "</$element>";
                        }

                        $diff_count = $diff_next + $diff_count;

                        break;
                        case($diff_next < 0):

                    //下位

                        $tag_after  = "";
                        $diff_count = $diff_next + $diff_count ;

                        break;


                        case($diff_next == 0):

                    //同位

                        $tag_after= "</$content>";

                        break;
                    }
                break;

                case(false):

                        $tag_after= "2</$content>";


                break;
            }


            if($running and !$prev_flag){


                    $line = $start.$tag_before.$current[2].$tag_after;

            }elseif($running and $key < count($lines) - 2 ){



                    $line = $tag_before.$current[2].$tag_after;

            }elseif($last_line and !$next_flag){

                        $repeat     = abs($diff_next) ;

                        $tag_after  =  "</$content>";
                        $tag_after .= str_repeat($end_element_set,$repeat);
                        $tag_after .= "</$element>";

                    $line = $tag_before.$current[2].$tag_after.$end;




            }

    }


        $result .= trim($line)."\n";
        unset($tag_before,$tag_afrer,$prev,$start);
        $enc = "";
}
        $result = $result;
        return $this->tag_clear($result)."\n\n";
}


function check_element_count_list($html,$element="ul",$content="li"){

    //閉じタグチェック
            preg_match_all("/(<$element><$content>)/u",$html,$start,PREG_SET_ORDER);
            preg_match_all("/(<\/$element><\/$content>)/u",$html,$end,PREG_SET_ORDER);
            $rep = count($end)-count($start)-1;

            switch(true){

            case(count($end) == count($start)):

            break;

            case(count($end) > count($start)):
            //閉じタグが多い
            $rep = str_repeat("<\/$element><\/$content>",$rep + 1);
            $html = preg_replace("/$rep</$element>$/m","</$element>",$html);

            break;

            case(count($end) < count($start)):
            //閉じタグが少ない
            $rep = str_repeat("</$element></$content>",abs($rep) - 1);
            $html = preg_replace("/<\/$element>$/m","",$html);
            $html = $html.$rep."</$element>";


            break;


            }
            return $html;
}

function text2html_list2($document, $separator = "\n",$element = "ul",$wm = '-',$content = 'li',$attr = '',$content_attr = '',$description = ''){

        $this->separator        = $separator;
        $this->element          = $element;
        $this->wm               = $wm;
        $this->content          = $content;
        $this->attr             = $attr;
        $this->content_attr     = $content_attr;
        $this->description      = $description;

    global $content_name;

     if(!empty($content_name) and !empty($description)){
        $description = $description.'-'.$content_name;
     }else{
        $description = $description.$content_name;
     }

        $lines 				= explode($separator,$document);
        $start 				= true;
        $this->content_no 	= 1;
        $start_tag 			= "<{$element} $attr id=\"$element-$description-".$this->content_no."\">";
        $end_tag			= '';
        $result 			= "";

    foreach($lines as $list){

      $list = $list. $separator;

        if(ereg("(^$wm{1})(.+)",$list,$regs) and !strpos($list,'-->')){

        if(!empty($content)){

			$start_content	= "<$content>";
			$end_content	= "</$content>\n";
        }else{
		
			$start_content	= "";
			$end_content	= "";
        }

        $res  = $this->text2html_list($regs[2],$this->separator,$this->element,$this->wm,$this->content,$this->attr,$this->content_attr,$this->description);

        	$list			= str_replace($regs[0],$start_tag.$start_content.trim($this->sublist($res)).$end_content,$list);
            $start_tag		= "";
            $end_tag		= "</{$element}>";

        }elseif(!empty($end_tag)){

            $list 			= $end_tag."\n".$list;
            $this->content_no++;
            $end_tag		= '';
            $start_tag 		= "<{$element} $attr id=\"$element-$description-".$this->content_no."\">";
        }else{
		
            $start_tag 		= "<{$element} $attr id=\"$element-$description-".$this->content_no."\">";

        }

        $result .=   $list;

    }

        return $this->tag_clear($result);
    }

    function sublist($document,$separator = "\n"){

        $element    = $this->element;
        $wm         = $this->wm;
        $content    = $this->content;
        $start 		= true;
        $lines 		= explode($separator,$document);
        $end_tag	= "";
        $result 	= "";
        $class 		= "";

	foreach($lines as $key=>$list){

        $list 		= $list. "\n";

        if(ereg("(^$wm{1})(.+)",$list,$regs)){

			if($start == false){$start_tag = "";}else{$start_tag = "<$element>";}
			
			if(!ereg("(^$wm{1})(.+)",$lines[$key+1])){$end_tag= "</$element>";}else{$end_tag= "";}
			
			if(!empty($content)){
	
				$start_content = "<$content>";
				$end_content = "</$content>";
			}else{
			
				$start_content = "";
				$end_content = "";
			}

            $list= str_replace($regs[0],$start_tag.$start_content.trim($this->sublist($regs[2]))."\n".$end_content,$list);

            $start = false;
			
        }elseif(!empty($end_tag)){

          $list = $end_tag. "\n".$list;
        }
            $result .=  $list;

	}

		return $this->tag_clear($result);
    }

function text2html_code($document = "", $separator = "\n",$element = "pre",$wm = 'code:',$content = 'code',$attr = '',$content_attr = '',$description = ''){

        $this->element  = $element;
        $this->wm       = $wm;
        $this->content  = $content;

    global $content_name;

     if(!empty($content_name) and !empty($description)){
        $description 	= $description.'-'.$content_name;
     }else{
        $description 	= $description.$content_name;
     }

    	$i				= 0;
    	$lines			= explode($separator,$document);
        $start 			= true;
        $this->content_no = 1;
        $start_tag 		= "<{$element} $attr id=\"$element-$description-".trim($this->content_no)."\">";
        $end_tag		= '';
        $result			= "";

    foreach($lines as $list){
	
      $list = $list. "\n";

        if(preg_match("/(^$wm{1})(.+)/um",$list,$regs)){

            if(!empty($content)){
                $i++;
                $start_content = "<$content title=\"line$i\">";
                $end_content = "</$content>\n";
            }else{
                $start_content = "";
                $end_content = "\n";
            }

            $doc 		= $regs[2];
            $doc 		= $this->my_wordwrap($doc);
            $doc 		= htmlspecialchars($doc);
            $doc 		= str_replace(array('/',"\t",'$','<'),array("&#47;","    ",'&#36;','&#lt'),$doc);
            $doc 		= str_replace("\n","</code><code>",$doc);//ワードラップは、改行だけ埋め込むので、タグを補充
            $list 		= str_replace($regs[0],$start_tag.$start_content.trim($doc).$end_content,$list);
            $start_tag 	= "";
            $end_tag 	= "</{$element}>";

        }elseif(!empty($end_tag)){
		
            $list 		= $end_tag."\n".$list;
            $this->content_no++;
            $end_tag	= '';
			$start_tag 	= "<{$element} $attr id=\"$element-$description-".trim($this->content_no)."\">";
			$i			= 0;
        }else{
		
            $start_tag 	= "<{$element} $attr id=\"$element-$description-".trim($this->content_no)."\">";
			$i			=0;
        }

        $result .=   $list;
      }

        return $this->tag_clear($result);
    }

function text2html_table($document, $separator = "\n",$element = "table",$wm = 'tr:',$content = 'tr',$attr = '',$content_attr = '',$description = ''){

    if(!preg_match("/$wm/si",$document)){ return $document;}

        $this->element      = $element;
        $this->wm           = $wm;
        $this->content      = $content;
        $this->content_no   = 1;
        $start              = true;
        $end_tag            = '';
        $result             = "";
        $row_no             = 1;
        global $content_name;

             if(!empty($content_name) and !empty($description)){
                $description = $description.'-'.$content_name;
             }else{
                $description = $description.$content_name;
             }

            $start_tag 		= "<{$element} $attr id=\"table-$description-".$this->content_no."\">";
            $lines			= explode($separator,$document);
            $group			= "<colgroup><col /></colgroup>";

    foreach($lines as $key=>$list){

            $list 			= $list. $separator;
            $write_group 	= false;

        if(ereg("(^$wm{1})(.+)",$list,$regs)){

            if(preg_match("/({$wm}summary:)(.+)/um",$list,$match)){
			
                    if($end_tag){

 $start_tag = "</table>\n<{$element} $attr summary=\"$match[2]\" id=\"table-$description-".$this->content_no."\">";

                    }else{

 $start_tag = "<{$element} $attr summary=\"$match[2]\" id=\"table-$description-".$this->content_no."\">";
                    }

				$write_group = true;
				unset($regs[2]);
				$list		 = "";

            }else{

                $ht_field = "";

                if(isset($regs[2])){

                    $fields = explode('|',$regs[2]);
                    $col_no	=1;
                    foreach($fields as $colkey=>$field){
					
 $ht_field .= "<td class=\"col{$col_no} row{$row_no}\" id=\"tbl".$this->content_no."{$col_no}{$row_no}\">$field</td>";
                    $col_no++;

                    }
					
                    $row_no++;
                }

                    $list 		= str_replace($regs[0],$start_tag."<$content>".$ht_field."</$content>\n",$list);
                    $start_tag 	= "";
                    $end_tag 	= "</{$element}>\n";

                if(!isset($lines[$key + 1]) or !ereg("(^$wm{1})(.+)",$lines[$key + 1])){

                    $list = str_replace($regs[0],$start_tag."<$content>".$ht_field."</$content>{$end_tag}\n",$list);
                    $row_no = 1;
                }
            }
        }elseif($end_tag){
		
            $list 		= $end_tag."\n".$list;
            $row_no 	= 1;

            $this->content_no++;

            $start_tag 	= "<{$element} $attr id=\"table-$description-".$this->content_no."\">";
            $end_tag	= false;
        }else{
		
            $start_tag = "<{$element} $attr id=\"table-$description-".$this->content_no."\">";
        }

        $result .=   $list;
    }
		return $this->tag_clear($result);
}

function text2html_element($document, $separator = "\n",$element = "h2",$wm = '*',$content = 'span',$attr = '',$content_attr = '',$description = ''){

     global $content_name;

     if(!empty($content_name) and !empty($description)){
        $description 	= $description.'-'.$content_name;
     }else{
        $description 	= $description.$content_name;
     }

    $lines = explode($separator,$document);
        $start			= true;
        $end_tag		= '';
        $result			= "";
        $start_tag 		= "<{$element} $attr id=\"$element-$description-".$this->content_no."\" >";
        $this->content_no = 1;

    foreach($lines as $key => $list){

      $list = $list. "\n";

        if(preg_match("/(^$wm{1})(.+)/um",$list,$regs)){
		
            if(!empty($content)){
			
                $content_start  = "<$content $content_attr >";
                $content_end    = "</$content>";
            }else{
			
                $content_start  = "";
                $content_end    = "";
            }
			
            $list 				= str_replace($regs[0],$start_tag.$content_start.$regs[2].$content_end,$list);
            $start_tag 			= "";
            $end_tag 			= "</{$element}>\n";

            //見出しリスト

        	if(ereg("h([1-6])",$element,$match)){
		
            	$list = str_replace("\n","",$list);
                array_push($this->header_info,array($key,trim($match[1]),"$element-$description-".$this->content_no,$regs[2]));
            }

        }elseif(!empty($end_tag)){
		
            $list 		= $end_tag."\n".$list;
            $this->content_no++;
            $end_tag	= '';
            $start_tag 	= "<{$element} $attr id=\"$element-$description-".$this->content_no."\" >";
        }else{
		
            $start_tag 	= "<{$element} $attr id=\"$element-$description-".$this->content_no."\" >";
        }
        	$result .=   $list;
    }

	return $this->tag_clear($result);
}

function paragraf($document, $separator = "\n\n",$element = "p",$wm = '',$content = '',$attr = '',$content_attr = '',$description = 'paragraph'){

     global $content_name;

     if(!empty($content_name) and !empty($description)){
        $description = $description.'-'.$content_name;
     }else{
        $description = $description.$content_name;
     }

    $checks=array('dl','address','blockquote','form','fieldset','table','style','tr','code','div');

    foreach($checks as $val){

        $check[]	= "<$val";
        $check[]	= "$val>";
        $check[]	= "</$val";

        $replace[] 	= "\n\n<$val";
        $replace[] 	= "$val>$separator";
        $replace[] 	= "$separator</$val";
    }


    $document 		= str_replace($check,$replace,$document);
    $document 		= $this->tag_clear($document);
    $document 		= ereg_replace("(\n{1})","\n\n",$document);
    $lines 			= explode($separator,$document);
	$start			= true;
	$end_tag		= '';
	$result			= "";
	$this->content_no = 1;
	$start_tag 		= "<{$element} $attr id=\"$element-$description-".$this->content_no."\">";
	//$wm 			= "[^(\*|+|<|\=|\n$|\s|code:|　　　)]";
	$blocks 		= true;//pをコンテンツに出来ないタグ内での変換を禁止
	$wm 			= "[^(\*|\+|\=|\n$|\s|　|\-|<)]";
	$tags_block 	= "(dl|ol|ul|address|blockquote|form|fieldset|table|style|tr|p|code)";
	$cdata_zone 	= false;

    foreach($lines as $key => $list){
	
      $list = $list."\n\n";

		if(preg_match("/(<!--|<!\[CDATA\[|<script|<style|<$tags_block)/iu",$list) and !preg_match("/(!--|\]\]>|\/script|\/style|<\/$tags_block)\s?\/?>/iu",$list)){
			$cdata_zone = true;
			//テーブル間にタグを適用できなくなる
		}

		if(preg_match("/(^($wm).*)/um",$list,$regs) and $cdata_zone == false ){

            $content_start 		= "";

            if(isset($lines[$key + 1]) and $lines[$key + 1] == true){

                $content_end    = "<br />";
            }else{

                $content_end    = "";
            }

				$list = str_replace($regs[0],$start_tag.$content_start.trim($regs[1]).$content_end,$list);
				$start_tag          = "";
				$end_tag            = "\n</{$element}>\n\n";
				$paragraph_div 		= '¶';
			
			if(eregi($paragraph_div,$list)){
	
				$list 				= str_replace(array($paragraph_div.$content_end,$paragraph_div),$end_tag, $list);
				$end_tag			= '';
				$this->content_no++;
				$start_tag 			= "<{$element} $attr id=\"$element-$description-".$this->content_no."\">";
			}

        }elseif(!empty($end_tag) ){

            $list = $end_tag."\n".$list;
            $end_tag= '';
            $this->content_no++;
            $start_tag = "<{$element} $attr id=\"$element-$description-".$this->content_no."\">";

        }else{

            $start_tag = "<{$element} $attr id=\"$element-$description-".$this->content_no."\">";
        }


        if(preg_match("/(-->|\]\]>|<\/script|<\/style|<\/$tags_block)/iu",$list)){

            $cdata_zone = false;
        }

        $result .=   $list;
    }

        return $this->tag_clear($result);
}

function img_copy($buffer){

	if(!defined('TEXTTOHTML_IMAGE_DIR_PATH')){return $buffer;}
	
    $copy_width = TEXTTOHTML_COPY_IMG_WIDTH;

    if(preg_match_all("/(copy>\()([^\)]+)(\))/", $buffer, $matches, PREG_SET_ORDER)){

       foreach($matches as $key=>$match){

			$cache = use_cache($matches[$key][0],$buffer);

        if($cache[0]){

        	$buffer= str_replace($matches[$key][0],$cache[1],$buffer)."\n";
        }else{
            clearstatcache();
			           
            $copy_target    	= TEXTTOHTML_IMAGE_DIR_PATH.basename($match[2]);
			$copy_target_url    = TEXTTOHTML_IMAGE_DIR_URL.basename($match[2]);
            $quote_comment  	= "<!--from:".$match[2]."--><a href=\"".$match[2]."\" class=\"quoted\">";
			$size 				= getimagesize($match[2]);
			$uri 				= htmlspecialchars(trim($match[2]));

            if($size[0] > $copy_width){
                $aspect = @round($size[1]/$size[0],2);
                $height = @round($copy_width *  $aspect,0);
            }else{
                $copy_width = $size[0];
                $height = $size[1];
            }
			
            $gdimg = imagecreatetruecolor($copy_width,$height);

            if($size[2] == 1)  {
			
             	if( $im = imagecreatefromgif($uri)){
					imagecopyresized($gdimg,$im,0,0,0,0,$copy_width,$height,$size[0],$size[1]);
					@imagegif($gdimg,$copy_target);
				}
            }
			
            if($size[2] == 2 and $size)  {
             
				if( $im = imagecreatefromjpeg($uri)){
					imagecopyresized($gdimg,$im,0,0,0,0,$copy_width,$height,$size[0],$size[1]);
					@imagejpeg($gdimg,$copy_target);
				}
            }
            if($size[2] == 3)  {
			
				if($im = imagecreatefrompng($uri)){
					imagecopyresized($gdimg,$im,0,0,0,0,$copy_width,$height,$size[0],$size[1]);
					@imagepng($gdimg,$copy_target);
				}	
            }
            if($size[2] == 15) {
			
				if($im = imagecreatefromwbmp($uri)){
					imagecopyresized($gdimg,$im,0,0,0,0,$copy_width,$height,$size[0],$size[1]);
					@imagebmp($gdimg,$copy_target);
				}	
            }
			
        $buffer= str_replace($matches[$key][0],$quote_comment."<img src=\"".$copy_target_url."\" width=\"$copy_width\" height=\"$height\" alt=\"copyed image\" /></a>",$buffer)."\n";			
			

        save_cache($matches[$key][0],$quote_comment."<img src=\"".$copy_target_url."\" width=\"$copy_width\" height=\"$height\" alt=\"copyed image\" /></a>");
        }

       }

    }
return $buffer;
}

function keyword_change($document){

		$keyword_res      = array();
		$change_val_res   = array();

    if(phpversion('domDocument')){

		$dom         	= new domDocument;
		$dom->load(CHANGE_PATTERN_PATH);
		$root        	= $dom->documentElement;
		$books       	= $root->childNodes;
		$keyword_res 	= array();
		$change_val  	= array();

       foreach ($books as $book) {

          if (@$book->nodeName == 'dl') {
           $content = $book->childNodes;

            foreach ($content as $elem) {
             if (@$elem->nodeName == 'dd') {
              $change_val[] = $elem->nodeValue;
             }
             if (@$elem->nodeName == 'dt') {
              $keyword[] = $elem->nodeValue;
              }
            }
          }
        }

        $result = str_replace($keyword , $change_val, $document);
        return $this->tag_clear($result);

    }else{

		$data 	= file_get_contents(CHANGE_PATTERN_PATH);
		$dls 	= explode("<dl>",$data);

      foreach($dls as $dl){

        ereg("(<dt>)([^<]+)(</dt>)",$dl,$keyword);
        array_push($keyword_res,$keyword[2]);
        ereg("(<dd>)([^<]+)(</dd>)",$dl,$change_val);
        array_push($change_val_res,$change_val[2]);
      }

	$keyword_res 	= str_replace(array("&gt;","&lt;","&amp;","&quot;"),array(">","<",'&','"'),$keyword_res);
	$change_val_res = str_replace(array("&gt;","&lt;","&amp;","&quot;"),array(">","<",'&','"'),$change_val_res);
    $res 			= str_replace($keyword_res,$change_val_res,$document);
    return $res;
    }
}


	function keyword_change_inline($document, $separator = "\n"){

        $before_start       = "<!--%";
        $before_end         = "%-->";
        $start_tag          = '【';
        $end_tag            = '】';

        $word               = "";
        $change             = "";
        $document_result    = "";
        $keyword_res        = array();
        $change_val_res     = array();
        $textdes            = explode($separator, $document);
        $record             = 0;

      foreach($textdes as $words){
        $words = $words . "\n";

        if($record == 0  and ereg("(^$start_tag)([^/]+)($end_tag)",$words,$keyword)){

            $change 		= "";
            $keyword 		= $before_start.$keyword[2].$before_end;
            $record 		= 1;
        }elseif($record == 1 and !ereg("(^$start_tag\/)(.+)($end_tag)",$words)){

            $change .= $words . "\n";
        }elseif($record == 1 and ereg("(^$start_tag\/)(.+)($end_tag)",$words)){

            $record = 0;

            if(array_search($keyword,$keyword_res) == false and !empty($keyword) and !empty($change)){

                array_push($keyword_res,$keyword);
                $change         = str_replace(array("\r\n","\r","\n"),"<><>",$change);
                array_push($change_val_res,$change);
                $array_res[]    = array($keyword=>$change);
            }
        }else{

          $document_result .= $words;
        }
       }
        $document_result = str_replace($keyword_res,$change_val_res,$document_result);
        $result = str_replace(array("<><>","><"),array("\n",">\n<"),$document_result);

	return $this->tag_clear($result);
}


function inline_tag($text){

$tags_inline = "(a|abbr|acronym|area|b|base|bdo|big|body|button|caption|cite|code|colgroup|dd|del|dfn|dt|em|head|html|i|img|input|ins|kbd|label|legend|li|link|map|object|optgroup|option|param|q|samp|select|small|span|strong|sub|sup|tbody|td|textarea|tfoot|th|thead|title|tt|var)";

    if(preg_match_all("/(\[)($tags_inline)(\|)([^\|]+)(\|)([^\]]+)(\])/", $text, $matches, PREG_SET_ORDER)){
        foreach($matches as $key=>$match){

			$element 		= mb_convert_encoding($match[2],"UTF-8","auto");
			$attr 			= mb_convert_encoding($match[5],"UTF-8","auto");
			$value 			= mb_convert_encoding($match[7],"UTF-8","auto");
			$replacement 	= "<$element $attr>$value</$element>";
			$text 			= str_replace($matches[$key][0],$replacement,$text)."\n";
        }
		
	    $code_hit = true;
    }
	
	return $text;
}


function ruby($text){

  if(preg_match_all("/(ruby>\()([^:]+)(:)([^\)]+)(\))/", $text, $matches, PREG_SET_ORDER)){
  
        foreach($matches as $key=>$match){

			$word			= mb_convert_encoding($match[2],"UTF-8","auto");
			$kana 			= mb_convert_encoding($match[4],"UTF-8","auto");
			$word 			= str_replace("\n","",$word);
			$kana 			= str_replace("\n","",$kana);
        	$replacement 	= "<ruby><rb>$word</rb><rp>（</rp><rt>$kana</rt><rp>）</rp></ruby>";
        	$text 			= str_replace($matches[$key][0],$replacement,$text)."\n";
        }

    	$code_hit = true;
    }
	
	return $text;
}


function trackback($text){

	if(!defined('TEXTTOHTML_TRACKBACK_URL')){return $text;}

    if(preg_match_all("/(trackback>\()([^\)]+)(\))/", $text, $matches, PREG_SET_ORDER)){
	
        foreach($matches as $key=>$match){
		
			$tabindex = $key + 1;

		  switch ($key) {
			case 0:
			   $accesskey = "a";
			   break;
			case 1:
			   $accesskey = "b";
			   break;
			case 2:
			   $accesskey = "c";
			   break;
			case 3:
			   $accesskey = "d";
			   break;
			case 4:
			   $accesskey = "e";
			   break;
			case 5:
			   $accesskey = "f";
			   break;
			default:
			   $accesskey = "g";
	
		  }

        $enc 		 = mb_convert_encoding($match[2],"UTF-8","auto");
        $enc 		 = urlencode($enc);
		
        $replacement = "<div class=\"trackback\"><span>トラックバック:".$match[2]."</span><br />Track back URL:<input type=\"text\" value=\"".TEXTTOHTML_TRACKBACK_URL. $enc. "\" accesskey=\"$accesskey\" tabindex=\"".$tabindex."\" /><br /><script type=\"text/javascript\" src=\"".TEXTTOHTML_TRACKBACK_URL. $enc. "\"></script>\n</div>\n";

        $text 		 = str_replace($matches[$key][0],$replacement,$text)."\n";
        }

    $code_hit = true;
    }
	return $text;

}
/*------------------------------------------------------------------------------+
 *URL　メールアドレスをリンクに置換
 *------------------------------------------------------------------------------*/
function maillink($text){

    if(preg_match_all("/(mail>\()([^@]+)@([^\)]+)(\))/", $text, $matches, PREG_SET_ORDER)){
        foreach($matches as $key=>$match){

        $enc = mb_convert_encoding($match[2]."&#64;".$match[3],"UTF-8","auto");
        $chenge_val = "<a href=\"mailto:$enc\">mailto:".$match[2]."</a>";


        $text= str_replace($matches[$key][0],$chenge_val,$text)."\n";


        }

    }
	
	return $text;
}



  /*------------------------------------------------------------
   * youtube link
   -------------------------------------------------------------*/

function youtube($text,$separator = "\n"){
 global $copy_width;

    if(preg_match_all("/(youtube>\()([^\)]+)(\))/", $text, $matches, PREG_SET_ORDER)){

        foreach($matches as $key=>$match){

            $query = parse_url($match[2]);
            $query = str_replace("v=","",$query['query']);
            $copy_target = "http://img.youtube.com/vi/".$query."/default.jpg";
            $quote_comment = "<a href=\"$match[2]\" target=\"blank\">";

            if($size = getimagesize($match[2])){
                $aspect = round($size[1]/$size[0],2);
                $height = $copy_width *  $aspect;
            }else{
                    $copy_width = 130;
                    $height = 97;
            }
 $text= str_replace($matches[$key][0],$quote_comment."{$copy_target}?w={$copy_width}h={$height}alt=YouTube </a>",$text)."\n";
        }
    }
	
	return $text;
}
/*------------------------------------------------------------------------------+
 * 文字列から、イメージの作成とコーディング処理
 *------------------------------------------------------------------------------*/
function txt2img($buffer,$separator = "\n"){

	global $default;
	
	if(!defined('TEXTTOHTML_FONTS_PATH') ){return $buffer;}else{

    	include(TEXTTOHTML_FONTS_PATH);
		$buffers 	= explode($separator,$buffer);
		$string 	= "";
    
		foreach($buffers as $buffer){
	
			if(preg_match_all("/(txt2img>\()([^\)]+)(\))/", $buffer, $matches, PREG_SET_ORDER)){
	
				foreach($matches as $key=>$match){
	
					if(ereg("(:)",$match[2])){
							list($element,$val_name,$val) =explode(":",$match[2]);
	
								$replacement = $this->convert_image($val,$$val_name,$element);
					}else{
								$replacement = $this->convert_image($match[2],$default,"p");
					}
	
					$string .= str_replace($matches[$key][0],$replacement,$buffer);
				}
	
	
			}else{
	
					$string .= $buffer."\n";
			}
		}

            return $string;

	}
}

/////////////////////////////////////////////////////////////

function convert_image( $string , $gd_set = array("gt200001","13","class=\"text2image\"","0"),$element = "p"){

	if(!defined('TEXTTOHTML_IMAGE_DIR_URL')){return $string;}

		$file_name		 = md5($string.$gd_set[0].$gd_set[1]);
		$image_file_name = str_replace(array('=','"','\\'),array(""),$gd_set[1])."-".$file_name.'.png';
		$image_file_name = TEXTTOHTML_IMAGE_DIR_URL.$image_file_name;
		$image_file_path = TEXTTOHTML_IMAGE_DIR_PATH.str_replace(array('=','"','\\'),array(""),$gd_set[1])."-".$file_name.'.png';
		$cache 			 = use_cache($file_name);

    if($cache[0]){
	
        $result= $cache[1]."\n";
        return $result;
    }else{

        $font           = TEXTTOHTML_FONT_DIR_PATH.$gd_set[0].'.ttf';
        $string         = mb_convert_encoding($string,"UTF-8","auto");
        $len            = mb_strlen($string);
        $fontsize       = $gd_set[1];
        $height         = $fontsize * 2;
        $background_img = $gd_set[3];
        $indent         = 20;
        $marginRight    = 20;
        $attribute      = $gd_set[2];

        switch(true){

			case($background_img == "0"): //背景画像を使用しない
			 
				$timg           = imagecreate($fontsize * 2 * $len,  $fontsize * 2);
				$background     = ImageColorAllocate($timg, 255, 255, 255);
				ImageFill($timg, 0, 0, $background);
				$Color 			= ImageColorAllocate($timg, 0, 0, 0);
			break;
	
			default://背景画像を使用する。
	
				$timg 			= imagecreatefrompng(TEXTTOHTML_FONT_DIR_PATH.$background_img);
				
				$Color			= ImageColorAllocate($timg, 0, 0, 0);
			break;
        }

        $vertical_align = $fontsize * 1.5;
        $chr 			= mb_convert_encoding($string,"UTF-8","auto");
        $box 			= ImageTTFText($timg, $fontsize, 0, $indent, $vertical_align, $Color, $font, $chr);
        $width 			= $box[2] + $marginRight;
        $timg_resized 	= ImageCreate($width, $fontsize * 2);
		
        imagecopy($timg_resized, $timg, 0, 0, 0, 0, $width, $fontsize * 2);
        imagepng($timg_resized,$image_file_path);

        if($timg_resized){

			$result = "<{$element} $attribute style=\"height:{$height}px;width:{$width}px;background:url($image_file_name);background-repeat:no-repeat;\">\n\t<span style=\"display:none;font-size:{$fontsize}px;\">$string</span></{$element}>\n";

        	save_cache($file_name,$result);

        	return $result;
        }else{
		
        	return $string;
        }

    }
}

/*------------------------------------------------------------------------------+
 *サウンドファイル　quicktime
 *------------------------------------------------------------------------------*/

function sound($text){

    if(preg_match_all("/(quicktime>\()([^\)]+)(\))/", $text, $matches, PREG_SET_ORDER)){
        foreach($matches as $key=>$match){

        $enc = mb_convert_encoding($match[2],"UTF-8","auto");

        $replacement = "<object classid=\"clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B\" width=\"176\" height=\"20\" codebase=\"http://www.apple.com/qtactivex/qtplugin.cab\"><param name=\"src\" value=\"$enc\" /><param name=\"autoplay\" value=\"false\" /><param name=\"controller\" value=\"true\" /><embed src=\"$enc\" width=\"176\" height=\"20\" autostart=\"false\" controller=\"true\" pluginspage=\"http://www.apple.com/quicktime/download/\"></embed>.</object>";

        $text = str_replace($matches[$key][0],$replacement,$text)."\n";
        }

    $code_hit = true;
    }
return $text;
}
/*------------------------------------------------------------------------------+
 *
 *------------------------------------------------------------------------------*/
 //3gp　foma 動画
function foma_movie($text){

$text = mb_eregi_replace("(https?|ftp)(://[[:alnum:]\+\$\;\?\.%,!#~*/:@&=_-]+\.(3gp))", "<object classid=\"clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B\" width=\"176\" height=\"160\" codebase=\"http://www.apple.com/qtactivex/qtplugin.cab\"><param name=\"src\" value=\"\\1\\2\" /><param name=\"autoplay\" value=\"false\" /><param name=\"controller\" value=\"true\" /><embed src=\"\\1\\2\" width=\"176\" height=\"160\" autostart=\"false\" controller=\"true\" pluginspage=\"http://www.apple.com/quicktime/download/\"></embed>.</object>\n",$text);

return $text;
}
/*------------------------------------------------------------------------------+
 *
 *------------------------------------------------------------------------------*/
function swf($text){

$text = mb_eregi_replace("(https?|ftp)(://[[:alnum:]\+\$\;\?\.%,!#~*/:@&=_-]+\.(swf))(\?w=)([0-9]{1,3})(h=)([0-9]{1,3})", "<object class= \"swf\" data=\"\\1\\2\" type=\"image/swf\" codebase=\"http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,0,0\"  height=\"\\7\" width=\"\\5\" classid=\"clsid:d27cdb6e-ae6d-11cf-96b8-444553540000\" ><param name=\"allowscriptaccess\" value=\"samedomain\" /><param name=\"movie\" value=\"\\1\\2\" /><param name=\"quality\" value=\"high\" /><param name=\"bgcolor\" value=\"#ffffff\" /><embed src=\"\\1\\2\" width=\"\\5\" height=\"\\7\" bgcolor=\"#ffffff\" loop=\"false\" quality=\"high\" pluginspage=\"http://www.macromedia.com/shockwave/download/index.cgi?p1_prod_version=shockwaveflash\" type=\"application/x-shockwave-flash\"></embed></object>\n",$text);


return $text;
}

/*------------------------------------------------------------------------------+
 *指定部分をURLENCODE
 *------------------------------------------------------------------------------*/

function encode_query($text){

    if(preg_match_all("/(query>\()([^\)]+)(\))/", $text, $matches, PREG_SET_ORDER)){
	
        foreach($matches as $key=>$match){

			$enc = mb_convert_encoding($match[2],"UTF-8","auto");
			$enc = urlencode($enc);
			$text= str_replace($matches[$key][0],$enc,$text)."\n";
        }

    }
	return $text;
}

/*------------------------------------------------------------------------------+
 *$show_img_tag   画像表示uriのみ class= "ins_img"
 *------------------------------------------------------------------------------*/

function image($text){

	$allow_img_filetype = "(\.gif|\.png|\.jpe?g)";

$text = eregi_replace("(https?://[[:alnum:]\+\$\;\?\.%,!#~*/:@&=_-]+)($allow_img_filetype)(\?w=)([0-9]{1,3})(h=)([0-9]{1,3})(alt=)?([^([:space:]|<)]+)?", "<img src=\"\\1\\2\" width=\"\\5\" height=\"\\7\" class=\"picture\" alt=\"\\9\" />",$text);

return $text;
}


//リンク名つきリンク
function link_title($text){

    if(preg_match_all("/(https?)(:\/\/[[:alnum:]\+\$\;\?\.%,!#~*\/:@&=_-]+)(\()(b:|t:|s:)?([^\)]+)(\))/", $text, $matches, PREG_SET_ORDER)){

        foreach($matches as $key=>$match){
		
           $cache = use_cache($matches[$key][0],$text);
		   
			if($cache[0]){
			
				$text 	= str_replace($matches[$key][0],$cache[1],$text)."\n";
			}else{

				switch($match[4]){
					case('b:'):
						$attr = '_blank';
					break;
					case('t:'):
						$attr = '_top';
					break;
					case('s:'):
						$attr = '_self';
					break;
		
					default:
						$attr = '_self';
		
					break;
				}
				
				$attr 		= "onclick=\"this.target='$attr';\" onkeypress=\"this.target='$attr';\"";
				$link_name 	= mb_convert_encoding($match[5],"UTF-8","auto");
				$url 		= $match[1].$match[2];
	
				if(trim($link_name) == 'title'){
	
					$cache = use_cache($matches[$key][0],$link_name);

						try{
							if(!$data = mb_convert_encoding(file_get_contents($url),"UTF-8","auto")){

								throw new Exception('リンクタイトルを取得できません');
							}

								preg_match( "/<title.*?>(.*?)<\/title>/si", $data, $regs );
								$linkname = trim(strip_tags($regs[1]));
								$link_name = htmlspecialchars($linkname);
	
						}catch (Exception $e) {
									$link_name = $url;
									echo '例外: ',$url,  $e->getMessage(), "\n";
						}
	
					if(empty($link_name)){  $link_name = $url;}
				}
	
				$link 	= "<a href=\"".$url."\" $attr >".$link_name."</a>";
				$text	= str_replace($matches[$key][0],$link,$text)."\n";
			}
	
		}
	
	}

        return $text;
}


function name_link($text){

	$text = eregi_replace("(link>)(https?)(://[[:alnum:]\+\$\;\?\.%,!#~*/:@&=_-]+)",  "<a href=\"\\2\\3\" title=\"\\2\\3\">\\2\\3</a>\n", $text);
	$text = mb_ereg_replace("(https?)(://[[:alnum:]\+\$\;\?\.%,!#~*/:@&=_-]+)(（)([^）]+)(）)", "<a href=\"\\1\\2\" title=\"\\1\\2\">\\4</a>\n",$text);

return $text;
}


function clear_both($text){

$text = str_replace("［クリア］", "<br style=\"clear:left;\" />", $text);
$text = str_replace("[クリア]", "<br style=\"clear:left;\" />", $text);

return $text;
}

/*
function read_php2($text){

    if(preg_match_all("/(eval>\[)([^\]]+)(\])/", $text, $matches, PREG_SET_ORDER)){
        foreach($matches as $key=>$match){

			$str = mb_convert_encoding($match[2],"UTF-8","auto");
			eval("\$str = $str;");
			$text= str_replace($matches[$key][0],$str,$text)."\n";
        }

    }
return $text;
}
*/
function read_php($text){

    if(preg_match_all("/(eval>\[)([^\]]+)(\])/", $text, $matches, PREG_SET_ORDER)){
        foreach($matches as $key=>$match){

        $str = mb_convert_encoding($match[2],"UTF-8","auto");
        if(isset($str) and !empty($str)){

            try {

                $replacement = $this->script_on($str);

                $text= str_replace($matches[$key][0],$replacement,$text)."\n";

            } catch (Exception $e) {
                echo '例外発生: ',  $e->getMessage(), "\n";
            }


            }
        }
    }
return $text;
}

function script_on($str){

    if (eval("\$replacement = $str;") === false ){
        throw new Exception(htmlspecialchars($str).'　phpとして評価できません');
    }

    return $replacement;
}


function repair_end($text){
    $text = str_replace("<p>[block]</p>", "", $text);
    $text = str_replace("<p>[block]", "", $text);
    $text = str_replace("[block]\n</p>", "", $text);
    $text = preg_replace("/(<br \/>){2,}/", "<br />", $text);

    return $text;

}

function note($text,$separator = "\n"){
  /* ------------------------------------------------------------
   * フットノート
   *-------------------------------------------------------------*/

    if(preg_match_all("/(《)([^》]+)(》)/su", $text, $matches, PREG_SET_ORDER)){

        foreach($matches as $key=>$match){
		
        	$enc 			= mb_convert_encoding($match[2],"UTF-8","auto");
        	$replacement 	= "<a class=\"foot-note\" href=\"#foot-note-$key\" name=\"anchor-foot-note-$key\" id=\"anchor-foot-note-$key\" title=\"脚注へ移動\">[$key]</a>";
        	$text 			= str_replace($matches[$key][0],$replacement,$text)."\n";

			array_push($this->footNote, array($key,"anchor-foot-note-$key","foot-note-$key",$enc));
        }

    	$code_hit = true;
    }

	return $text;
}

/*------------------------------------------------------------------------------+
 *  エンコーディング変更　$_GET['e']で切り替え
 *------------------------------------------------------------------------------*/
    function result_encoding($text){

        if(isset($_GET['e'])
                and ($_GET['e'] == "s" or
                    $_GET['e'] == "e" or
                    $_GET['e'] == "u" or
                    $_GET['e'] == "j" )){

          $e = $_GET['e'];
          switch ($e) {
              case "s":

              return mb_convert_encoding($text,"SHIFT_JIS","UTF-8");

              break;
              case "e":
              return mb_convert_encoding($text,"UTF-8","UTF-8");
              break;
              case "u":
              return $text;
              break;
              case "j":
              return mb_convert_encoding($text,"JIS","UTF-8");
              break;

              default:
              return $text;
              }
        }else{

            return $text;
        }
    }

  /* ------------------------------------------------------------
   * 整形記号のチェック
   -------------------------------------------------------------*/

    function basic_cleaner($buffer,$separator = "\n"){
	
    	global $parm;
		
        $buffer = mb_convert_encoding($buffer,"UTF-8","auto");
        $file 	= explode($separator,$buffer);
    	$text 	= "";
		
        foreach($file as $key => $chk){

          $chk = str_replace("\0", "", $chk);
          $chk = "\n$chk";
          $chk = preg_replace("(^\s|\s{2,100}^\t| $|&emsp;$|\.{2}\/)", "" , $chk);
          $chk = preg_replace("'([\r\n])[\s]+'", "\n", $chk);
          $chk = preg_replace("'([\r\n])[\s]+'", "\n", $chk);

          $text .= "\n$chk";

        }
		
    	return $text;
    }
/*------------------------------------------------------------------------------+
 * イメージサイズの検出
 *------------------------------------------------------------------------------*/
function my_imagesize2($file, $wide ="width=\"200\"" ){

  if(eregi("\.(gif|jpg|png|swc|psd|tiff|bmp|iff|jp2|jpx|jb2|jpc|xbm|wbmp)",$file)){
    list($width, $height, $type, $attr) = getimagesize($file);
  	return $attr;
  }else{
  	return $wide;
  }
}


/*------------------------------------------------------------------------------+
 *ソースの表示　url等に、改行をはさんでオーバーフローを防止する。
 *------------------------------------------------------------------------------*/

function my_wordwrap($str){

    $wrap_width = TEXTTOHTML_CODE_WRAP_WIDTH;

    if(isset($wrap_width)){
        $old = array();
        $new = array();
                preg_match_all("/([A-z0-9\/-_=\?:#;\.]+)/u", $str, $matches);
                $newtext = "";
                $result = "";
                foreach($matches as $match){

                    foreach($match as $line){

                        if(strlen($line) > $wrap_width){
                            $old[] = $line;
                            $new[]= wordwrap($line, $wrap_width, "\n", 1);
                        }
                    }
                }

            $result = str_replace($old,$new,$str);

            return $this->tag_clear($result);
    }else{

            return $str;
    }
}
/*------------------------------------------------------------------------------+
 *　ソースの簡易整形
 *------------------------------------------------------------------------------*/
function style_set($str){

    $tab 	= "&nbsp;&nbsp;&nbsp;&nbsp;";
    $i 		= 0;
    $break 	= "";
    $str 	= str_replace("<","@@@@@<",$str);
    $result ="";
    $lines 	= explode("@@@@@",$str);

	foreach($lines as $key=>$line){

        if(preg_match("/(<\/?(xml|html|body))/mi",$line) ){

                $i 			= 0;
                $space 		= str_repeat($tab,$i);
                $break 		= "<br />\n";

                }elseif(preg_match("/(<\/?(xml|html|head|body|script|!doctype))/mi",$line) ){

                    $i 		= 2;
                    $space 	= str_repeat($tab,$i);
                    $break 	= "<br />\n";
                }elseif(preg_match("/(<\/)/",$line) ){

                    if($i<0){
						$i = 0;
					}
					
					$space 	= str_repeat($tab,$i);
					$break 	= "<br />\n";
					$i--;
                }elseif(preg_match("/(\/>?)/",$line) ){

                    if($i<0){
						$i 	= 0;
					}
					
                    $space 	= str_repeat($tab,$i);
                    $break 	= "<br />\n";
                }else{
                    $break 	= "<br />\n";

                    if($i<0){
						$i 	= 0;
					}
					
                    $space 	= str_repeat($tab,$i);
                    $i++;

                }

        	$result .= $space.htmlspecialchars($line).$break;
        }

	return $this->tag_clear($result);
}

  /* ------------------------------------------------------------
   *タグ内の改行を削除
   -------------------------------------------------------------*/

function tag_clear($text){
    clearstatcache ();

//行頭スペースを削除 全角スペース以外
    $text = preg_replace("/(^[[:space:]]+)(.*)/m","\\2",$text);

//複数の改行を、ひとつに。
    $text = str_replace("\r","\n",$text);
    $text = preg_replace("/(\n){2,}/","\n\n",$text);

	return $text;
}

//end class
}


///////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////

//配列キー文字数の多い順にソート　uksort用

  function text2html_cmp($a, $b){
    $a = mb_strlen($a,"UTF-8");
    $b = mb_strlen($b,"UTF-8");

    //長い順
    return strcasecmp($b,$a);
    }


function postal_code($replacement){

 $replacement = mb_convert_encoding($replacement,"UTF-8","auto");
    if(preg_match("/(state=\")([^\"]+)/u",$replacement,$state) == 1){$state = $state[2];}else{$state = "";}

    if(preg_match("/(city=\")([^\"]+)/u",$replacement,$city) == 1){
        $city = $city[2];
        }else{
        $city = "";
        }
    if(preg_match("/(address=\")([^\"]+)/u",$replacement,$address) == 1){
        $address = $address[2];
        }else{
        $address = "";
        }
    if(preg_match("/(company=\")([^\"]+)/u",$replacement,$company) == 1){
        $company = $company[2];
        }else{
        $company = "";
        }

    if(preg_match("/(state_kana=\")([^\"]+)/u",$replacement,$state_kana) == 1){
        $state_kana = $state_kana[2];
        }else{
        $state_kana = "";
        }
    if(preg_match("/(city_kana=\")([^\"]+)/u",$replacement,$city_kana) == 1){
        $city_kana = $city_kana[2];
        }else{
        $city_kana = "";
        }
    if(preg_match("/(address_kana=\")([^\"]+)/u",$replacement,$address_kana) == 1){
        $address_kana= $address_kana[2];
        }else{
        $address_kana= "";
        }
    if(preg_match("/(company_kana=\")([^\"]+)/u",$replacement,$company_kana) == 1){
        $company_kana= $company_kana[2];
        }else{
        $company_kana= "";
        }

$title = "title=\"".$state_kana.$city_kana.$address_kana.$company_kana."\"";

return str_replace("none","","<span $title>".$state.$city.$address.$company."</span>");

}


//wikipedia
    function simpleapi_wikipedia($replacement, $count = 1){

        $result 	= unserialize($replacement);
        $results 	= "<div style=\"margin:1em;\">";

        for($i=0;$i<$count;$i++){
		
			$title = $result[$i]['title'];
			$body  = $result[$i]['body'];
			$results .= "<strong>Wikipedia:{$title}</strong><blockquote>".nl2br($body)."</blockquote>";
        }

        return str_replace(array("<br>","<br/>"),"<br />",$results)."\n</div>";
    }

/*
function test1(){

return date("ymd");

}
*/

////////////////////////////////////////////////////////////////////////////////////
function use_cache($name){

	if(!defined('CACHE_LITE_PATH')){return array(false,"");}
	
    require_once(CACHE_LITE_PATH);

	$options = array(
		'cacheDir' => CACHE_DIR_PATH,
		'lifeTime' => CACHE_LIFE_TIME,
	);

	$Cache_Lite = new Cache_Lite($options);

	if(!CACHE_SWITCH){
	
		$Cache_Lite->clean();
		return array(false,"");
	}

    $name = md5($name);

	if ($data = $Cache_Lite->get($name)){
		$result = $data;
		$flag = true;
	}else {

		$flag = false;
	}

    return array($flag,$data);
}

function save_cache($name,$value){

	if(!defined('CACHE_LITE_PATH')){return array(false,$value);}

    $name = md5($name);

    require_once(CACHE_LITE_PATH);

	$options = array(
		'cacheDir' => CACHE_DIR_PATH,
		'lifeTime' => CACHE_LIFE_TIME,
	);

    $Cache_Lite = new Cache_Lite($options);
	
	if(!CACHE_SWITCH){
	
		$Cache_Lite->clean();
		return array(false,$value);
	}

	if ($data = $Cache_Lite->get($name)){
		$result = $data;
		$flag = true;
	}else {

		$Cache_Lite->save($value,$name);
		//print_r($Cache_Lite);
		$result = $value;
		$flag = false;
	}

    return array($flag,$value);
}

function html_document1($ini_array,$documents,$navi="",$source = ""){

	global $content_name;
	global $source;
	global $campany_data;
	
	$charset        = $ini_array['html_header']['charset'];
	$author         = $ini_array['html_header']['author'];
	$keyword        = $ini_array['html_header']['keyword'];
	$description    = $ini_array['html_header']['description'];
	$mail           = $ini_array['html_header']['mail'];
	$stylesheet     = $ini_array['html_header']['stylesheet'];
	$style_media    = $ini_array['html_header']['style_media'];
	$navi_start     = $ini_array['html_header']['start'];
	$navi_prev      = $ini_array['html_header']['prev'];
	$navi_next      = $ini_array['html_header']['next'];
	$navi_help      = $ini_array['html_header']['help'];
	$title          = $ini_array['html_header']['title'];
	$embed          = $ini_array['html_header']['embed'];

$html=<<<DOC
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html lang="ja" xml:lang="ja" xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="content-type" content="text/html; charset=$charset" />
    <meta http-equiv="content-script-type" content="text/javascript" />
    <meta http-equiv="content-style-type" content="text/css" />
    <meta name="author" content="$author" />
    <meta name="keywords" content="$keyword" />
    <meta name="description" content="$description" />
    <link rev="made" href="mailto:$mail" />
    <link rel="stylesheet" href="$stylesheet" media="$style_media" type="text/css" />
    <link rel="start" href="$navi_start" />
    <link rel="prev" href="$navi_prev" />
    <link rel="next" href="$navi_next" />
    <link rel="help" href="$navi_help" />
    <title>$title</title>
    <script src="/js/jquery.js"                 type="text/javascript"></script>
    <script src="/js/jquery.flatheights.js"     type="text/javascript"></script>
    <link rel="stylesheet" href="/js/ui.tabs.css" type="text/css"
    media="print, projection, screen" />
    <link rel="stylesheet" type="text/css" href="/js/jquery.jcarousel.css" />
    <link rel="stylesheet" type="text/css" href="/js/skins/tango/skin.css" />
    $embed
</head>
<body id="top">
<div id="wrap">
<div id="header">
<h1>$title</h1>
</div>
<div id="common">
$navi
$documents
$source
</div>
<div id="footer">
2008&copy;$title
</div>
</div>
</body>
</html>
DOC;

$html = str_replace(array("<br >","<br>"),"<br />",$html);

echo $html;
}

?>