<?php
/**
 * @version $Id: Myuploader_TextFilter.class.php 661 2010-09-27 06:32:54Z hodaka $
 * @author hodaka <hodaka@kuri3.net>
 */

if (!defined('XOOPS_ROOT_PATH')) exit();

class Myuploader_TextFilter extends XCube_ActionFilter {
    function preBlockFilter() {
        $this->mRoot->mTextFilter->mMakeXCodeConvertTable->reset();
        $this->mRoot->mTextFilter->mMakeXCodeConvertTable->add('Myuploader_TextFilter::makeXCodeConvertTable');
        $this->mRoot->mDelegateManager->add('Legacy_TextFilter.MakePreXCodeConvertTable', 'Myuploader_TextFilter::makePreXCodeConvertTable', XCUBE_DELEGATE_PRIORITY_1);
        $this->mRoot->mTextFilter->mMakePostXCodeConvertTable->reset();
        $this->mRoot->mDelegateManager->add('Legacy_TextFilter.MakePostXCodeConvertTable', 'Myuploader_TextFilter::makePostXCodeConvertTable', XCUBE_DELEGATE_PRIORITY_FINAL - 1);
    }

    function preFilter() {
        $this->mRoot->mDelegateManager->add('Legacy_RenderSystem.SetupXoopsTpl', array(&$this, 'assignHeader'));
    }

    function makeXCodeConvertTable(&$patterns, &$replacements) {
//    	$patterns[] = "/\[siteimg align=(['\"]?)(left|center|right)\\1]([^\"\(\)\?\&'<>]*)\[\/siteimg\]/sU";
//        $replacements[0][] = '<a href="'.XOOPS_URL.'/\\3" target="_blank">'.XOOPS_URL.'/\\3</a>';
//        $replacements[1][] = '<img src="'.XOOPS_URL.'/\\3" align="\\2" alt="" >';
//        $patterns[] = "/\[siteimg]([^\"\(\)\?\&'<>]*)\[\/siteimg\]/sU";
//        $replacements[0][] = '<a href="'.XOOPS_URL.'/\\1" target="_blank">'.XOOPS_URL.'/\\1</a>';
//        $replacements[1][] = '<img src="'.XOOPS_URL.'/\\1" alt="" />';
//        $patterns[] = "/\[siteurl\=(['\"]?)([^\"'<>]*)\\1\](.*)\[\/siteurl\]/sU";
//        $replacements[0][] = $replacements[1][] = '<a href="'.XOOPS_URL.'/\\2" target="_blank">\\3</a>';
        $patterns[] = "/\[body\](.*)\[\/body\]/sU";
        $replacements[0][] = $replacements[1][] = '<div class="blogBody">\\1</div>';
        $patterns[] = "/\[url\=(['\"]?)(http[s]?:\/\/[^\"'<>]*)\\1\](.*)\[\/url\]/sU";
        $replacements[0][] = $replacements[1][] = '<a href="\\2" target="_blank">\\3</a>';
        $patterns[] = "/\[url\=(['\"]?)(ftp?:\/\/[^\"'<>]*)\\1\](.*)\[\/url\]/sU";
        $replacements[0][] = $replacements[1][] = '<a href="\\2" target="_blank">\\3</a>';
        $patterns[] = "/\[url\=(['\"]?)([^\"'<>]*)\\1\](.*)\[\/url\]/sU";
        $replacements[0][] = $replacements[1][] = '<a href="http://\\2" target="_blank">\\3</a>';
        $patterns[] = "/\[color\=(['\"]?)([a-zA-Z0-9]*)\\1\](.*)\[\/color\]/sU";
        $replacements[0][] = $replacements[1][] = '<span style="color: #\\2;">\\3</span>';
        $patterns[] = "/\[size\=(['\"]?)([a-z-]*)\\1\](.*)\[\/size\]/sU";
        $replacements[0][] = $replacements[1][] = '<span style="font-size: \\2;">\\3</span>';
        $patterns[] = "/\[font\=(['\"]?)([^;<>\*\(\)\"']*)\\1\](.*)\[\/font\]/sU";
        $replacements[0][] = $replacements[1][] = '<span style="font-family: \\2;">\\3</span>';
        $patterns[] = "/\[email\]([^;<>\*\(\)\"']*)\[\/email\]/sU";
        $replacements[0][] = $replacements[1][] = '<a href="mailto:\\1">\\1</a>';
        $patterns[] = "/\[em\](.*)\[\/em\]/sU";
        $replacements[0][] = $replacements[1][] = '<em>\\1</em>';
        $patterns[] = "/\[em\=([\"']?)([a-zA-Z0-9]*)\\1\](.*)\[\/em\]/sU";
        $replacements[0][] = $replacements[1][] = '<span style="color:#\\2;">\\3</span>';
        $patterns[] = "/\[b\](.*)\[\/b\]/sU";
        $replacements[0][] = $replacements[1][] = '<strong style="font-weight:bold">\\1</strong>';
        $patterns[] = "/\[i\](.*)\[\/i\]/sU";
        $replacements[0][] = $replacements[1][] = '<span style="font-style:italic">\\1</span>';
        $patterns[] = "/\[u\](.*)\[\/u\]/sU";
        $replacements[0][] = $replacements[1][] = '<span style="text-decoration:underline">\\1</span>';
        $patterns[] = "/\[d\](.*)\[\/d\]/sU";
        $replacements[0][] = $replacements[1][] = '<del>\\1</del>';
        $patterns[] = "/\[img align\=(['\"]?)(left|center|right)\\1\]([^\"\(\)\?\&'<>]*)\[\/img\]/sU";
        $replacements[0][] = '<a href="\\3" target="_blank" rel="nofollow">\\3</a>';
        $replacements[1][] = '<img src="\\3" align="\\2" alt="" />';
        $patterns[] = "/\[img\]([^\"\(\)\?\&'<>]*)\[\/img\]/sU";
        $replacements[0][] = '<a href="\\1" target="_blank" rel="nofollow">\\1</a>';
        $replacements[1][] = '<img src="\\1" alt="" />';
        $patterns[] = "/\[img align\=(['\"]?)(left|center|right)\\1 id\=(['\"]?)([0-9]*)\\3\]([^\"\(\)\?\&'<>]*)\[\/img\]/sU";
        $replacements[0][] = '<a href="'.XOOPS_URL.'/image.php?id=\\4" target="_blank" rel="nofollow">\\5</a>';
        $replacements[1][] = '<img src="'.XOOPS_URL.'/image.php?id=\\4" align="\\2" alt="\\5" />';
        $patterns[] = "/\[img id\=(['\"]?)([0-9]*)\\1\]([^\"\(\)\?\&'<>]*)\[\/img\]/sU";
        $replacements[0][] = '<a href="'.XOOPS_URL.'/image.php?id=\\2" target="_blank" rel="nofollow">\\3</a>';
        $replacements[1][] = '<img src="'.XOOPS_URL.'/image.php?id=\\2" alt="\\3" />';
        $patterns[] = "/\[quote]/sU";
        $replacements[0][] = $replacements[1][] = _QUOTEC.'<span class="blogQuote">';   // div -> span(display block)
        $patterns[] = "/\[\/quote]/sU";
        $replacements[0][] = $replacements[1][] = '</span>';    // /div -> /span
        $patterns[] = "/\[blockquote]/sU";
        $replacements[0][] = $replacements[1][] = '<blockquote class="blogQuote">';
        $patterns[] = "/\[\/blockquote]/sU";
        $replacements[0][] = $replacements[1][] = '</blockquote>';
//        $patterns[] = "/\[quote\]/sU";
//        $replacements[0][] = $replacements[1][] = _QUOTEC.'<div class="xoopsQuote"><blockquote>';
//        $patterns[] = "/\[\/quote\]/sU";
//        $replacements[0][] = $replacements[1][] = '</blockquote></div>';
        $patterns[] = "/javascript:/si";
        $replacements[0][] = $replacements[1][] = "java script:";
        $patterns[] = "/about:/si";
        $replacements[0][] = $replacements[1][] = "about :";
    }

    function makePreXCodeConvertTable(&$patterns, &$replacements) {
        $patterns[] = "/\[site(img|fig)(.*)\]([^\"\(\)\?\&'<>]*)\[\/site\\1\]/sU";
        $replacements[] = '[$1$2]'.XOOPS_URL.'/$3[/$1]';

        $patterns[] = "/\[siteurl\=(['\"]?)([^\(\)\"'<>]*)\\1\](.*)\[\/siteurl\]/sU";
        $replacements[] = '[url='.XOOPS_URL.'/$2]$3[/url]';

        $patterns[] = "/\[url\=(['\"]?)([^\(\)\"'<>]*)\\1\]\[(img|fig) ([^[\]]+)\]([^\"\(\)\?\&'<>]*)\[\/\\3\]\[\/url\]/sU";
        $replacements[] = '[$3 url=$2 $4]$5[/$3]';

        $patterns[] = "/\[(img|fig) ([^[\]]+)\]([^\"\(\)\?\&'<>]*)\[\/\\1\]/esU";
        $replacements[] = "Myuploader_TextFilter::_preEncode('$1', '$2', '$3')";
    }

    function _preEncode($tag, $attributes, $src) {
        $regexes[] = "/^align=(['\"]?)(left|center|right)\\1$/";
        $regexes[] = "/^align=(['\"]?)(left|center|right)\\1 id=(['\"]?)([0-9]*)\\3$/";
        $regexes[] = "/^id=(['\"]?)([0-9]*)\\1$/";

        if($tag == 'img') {
            foreach($regexes as $regex) {
                if(preg_match($regex, $attributes)) {
                    return sprintf('[img %s]%s[/img]', $attributes, $src);
                }
            }
        }

        return sprintf('[%s %s]%s[/%s]', $tag, base64_encode($attributes), $src, $tag);
    }

    function makePostXCodeConvertTable(&$patterns, &$replacements) {
        $patterns[] = "/\[code\](.*)\[\/code\]/esU";
//        $replacements[0][] = "'<div class=\"xoopsCode\"><pre><code>'.Legacy_TextFilter::codeSanitizer('$1', 0).'</code></pre></div>'";
//        $replacements[1][] = "'<div class=\"xoopsCode\"><pre><code>'.Legacy_TextFilter::codeSanitizer('$1', 1).'</code></pre></div>'";
        $replacements[0][] = "'<pre class=\"blogCode\"><code>'.Legacy_TextFilter::codeSanitizer('$1', 0).'</code></pre>'";
        $replacements[1][] = "'<pre class=\"blogCode\"><code>'.Legacy_TextFilter::codeSanitizer('$1', 1).'</code></pre>'";

        $patterns[] = "/\[(img|fig) ([^[\]]+)\](.*)\[\/\\1\]/esU";
        $replacements[0][] = "Myuploader_TextFilter::_markupByAttr('$1', '$2', '$3', false)";
        $replacements[1][] = "Myuploader_TextFilter::_markupByAttr('$1', '$2', '$3')";
    }

    function _markupByAttr($tag, $attributes, $src, $image_allowed=true) {
        $attrs_array = Myuploader_TextFilter::_getAttr($attributes);

        $wh = '';
        if(in_array('width', array_keys($attrs_array))) {
            $wh .= 'width="'.intval($attrs_array['width']).'" ';
        }
        if(in_array('height', array_keys($attrs_array))) {
            $wh .= 'height="'.intval($attrs_array['height']).'"';
        }

        // set target
        $target = '';
        if(!in_array('url', array_keys($attrs_array)) || false === strpos($attrs_array['url'], XOOPS_URL)) {
            $target = ' target="_blank"';
        }

        switch($tag) {
            case 'img':
                if($image_allowed) {
                    if(in_array('url', array_keys($attrs_array))) {
                        $markup = sprintf('<a href="%s" rel="nofollow"', $attrs_array['url']);

                        if(in_array('class', array_keys($attrs_array))) {
                            $markup .= sprintf(' class="%s"', $attrs_array['class']);

                            // highslide
                            if($attrs_array['class'] == 'highslide' && in_array('id', array_keys($attrs_array))) {
                                $markup .= sprintf(' id="%s" onclick="return hs.expand(this)"', $attrs_array['id']);
                            }
                        } elseif(in_array('id', array_keys($attrs_array))) {
                            $markup .= sprintf(' id="%s"', $attrs_array['id']);
                        }

                        $markup .= sprintf('%s><img src="%s" alt="%s" %s',
                            $target,
                            htmlspecialchars($src, ENT_QUOTES),
                            @$attrs_array['alt'],
                            $wh);
                        if(in_array('title', array_keys($attrs_array))) {
                            $markup .= sprintf(' title="%s"', $attrs_array['title']);
                        }
                        if(in_array('align', array_keys($attrs_array))) {
                            $markup .= sprintf(' align="%s"', $attrs_array['align']);
                        }

                        $markup .= ' /></a>';

                    } else {
                        $markup = sprintf('<img src="%s" alt="%s" %s',
                            htmlspecialchars($src, ENT_QUOTES),
                            @$attrs_array['alt'],
                            $wh);
                        if(in_array('align', array_keys($attrs_array))) {
                            $markup .= sprintf(' align="%s"', $attrs_array['align']);
                        }

                        $markup .= ' />';
                    }

                } else {
                    $markup = sprintf('<a href="%s" title="%s" rel="nofollow"%s>%s</a>',
                        htmlspecialchars($src, ENT_QUOTES),
                        @$attrs_array['title'],
                        $target,
                        htmlspecialchars($src, ENT_QUOTES));
                }

                return $markup;
                break;

            case 'fig':
                if($image_allowed) {
                   $markup = sprintf('<div class="figure%s">', isset($attrs_array['align'])? ' fig'.$attrs_array['align'] : "");

                    if(in_array('url', array_keys($attrs_array))) {
                        $markup .= sprintf('<a href="%s" rel="nofollow"', $attrs_array['url']);

                        if(in_array('class', array_keys($attrs_array))) {
                            $markup .= sprintf(' class="%s"', $attrs_array['class']);

                            // highslide
                            if($attrs_array['class'] == 'highslide' && in_array('id', array_keys($attrs_array))) {
                                $markup .= sprintf(' id="%s" onclick="return hs.expand(this)"', $attrs_array['id']);
                            }
                        } elseif(in_array('id', array_keys($attrs_array))) {
                            $markup .= sprintf(' id="%s"', $attrs_array['id']);
                        }

                        $markup .= sprintf('%s><img src="%s" alt="%s" %s',
                            $target,
                            htmlspecialchars($src, ENT_QUOTES),
                            @$attrs_array['alt'],
                            $wh);
                        if(in_array('title', array_keys($attrs_array))) {
                            $markup .= sprintf(' title="%s"', $attrs_array['title']);
                        }
                        $markup .= ' /></a>';
                    } else {
                        $markup .= sprintf('<img src="%s" alt="%s" %s/>', htmlspecialchars($src, ENT_QUOTES), @$attrs_array['alt'], $wh);
                    }

                    if(in_array('credit', array_keys($attrs_array))) {
                        $markup .= sprintf('<p class="credit"><abbr class="type" title="Photograph">Photo</abbr> by <cite>%s</cite></p>', $attrs_array['credit']);
                    }

                    if(in_array('title', array_keys($attrs_array)) && in_array('caption', array_keys($attrs_array))) {
                        $markup .= sprintf('<p class="caption"><em class="title">%s</em>%s</p>', $attrs_array['title'], $attrs_array['caption']);
                    } elseif(in_array('title', array_keys($attrs_array))) {
                        $markup .= sprintf('<p class="caption"><em class="title">%s</em></p>', $attrs_array['title']);
                    } elseif(in_array('caption', array_keys($attrs_array))) {
                        $markup .= sprintf('<p class="caption">%s</p>', $attrs_array['caption']);
                    }

                    $markup .= '</div>';


                } else {
                   $title = isset($attrs_array['title'])? $attrs_array['title'] : (isset($attrs_array['alt'])? $attrs_array['alt'] : (isset($attrs_array['caption'])? $attrs_array['caption'] : ''));
                    $markup = sprintf('<a href="%s" title="%s" rel="nofollow"%s>%s</a>',
                        htmlspecialchars($src, ENT_QUOTES),
                        $attrs_array['title'],
                        $target,
                        htmlspecialchars($src, ENT_QUOTES));
                }

                return $markup;
                break;

        }
    }

    function _getAttr($attributes) {
        $keypatterns = array(
            'url' => "/^[^\(\)\"'<>]*\s*$/",
            'width' => "/^\d{1,4}\s*$/",
            'height' => "/^\d{1,4}\s*$/",
            'align' => "/^(left|center|right)\s*$/",
            'alt' => "/^[^\(\)<>;:]*\s*$/",
            'title' => "/^[^\(\)<>;:]*\s*$/",
            'caption' => "/^[^\(\)<>;:]*\s*$/",
            'credit' => "/^[^\(\)<>;:]*\s*$/",
            'class' => "/^[0-9A-Za-z_-]+\s*$/",
            'id' => "/^[0-9A-Za-z_-]+\s*$/"
        );

        $attributes = base64_decode($attributes);
        $regex = '/('.implode('|', array_keys($keypatterns)).')\=(\\\"|\')?([^\s]*)(?(2)\\2|(\s|$))/';
        preg_match_all($regex, $attributes, $matches, PREG_SET_ORDER);
        $attrs_array = array();
        foreach($matches as $match) {
            if(preg_match($keypatterns[$match[1]], $match[3])) {
                $attrs_array[$match[1]] = htmlspecialchars(str_replace('\"', '"', stripslashes($match[3])), ENT_QUOTES);
            }
        }

        return $attrs_array;
    }

    function assignHeader() {
        $tpl =& $this->mRoot->_mRenderSystems['Legacy_RenderSystem']->mXoopsTpl;
        if(is_object($tpl)) {
            $highslidepath = '/common/highslide';   // Set highslide path. Coment out this line if you don't use highslide.
            $csspath = '';  // Set mytextfilter.css path
            $metaheader = $tpl->get_template_vars('xoops_module_header');
            $metaheader .= sprintf('<link href="%s%s/mytextfilter.css" rel="stylesheet" type="text/css" media="all" />', XOOPS_URL, $csspath)."\n";
            if (isset($highslide)) {
                $metaheader .= sprintf('<link href="%s%s/css/style.css" rel="stylesheet" type="text/css" media="all" />', XOOPS_URL, $highslidepath)."\n";
                $metaheader .= sprintf('<script type="text/javascript" src="%s%s/highslide.js"></script>', XOOPS_URL, $highslidepath)."\n";
                $metaheader .= sprintf('<script type="text/javascript" src="%s%s/highslide_option.js"></script>', XOOPS_URL, $highslidepath)."\n";
            }
            $tpl->assign('xoops_module_header', $metaheader);
        }
    }

}

?>