<?php
// $Horde: imp/lib/MIME/Viewer/text.php,v 1.7.2.15 2003/01/03 13:23:14 jan Exp $

/**
 * The IMP_MIME_Viewer_text class renders out plain text with
 * URLs made into hyperlinks.
 *
 * @author  Anil Madhavapeddy <anil@recoil.org>
 * @version $Revision: 1.7.2.15 $
 * @since   IMP 3.0
 * @package horde.mime.viewer
 */

class IMP_MIME_Viewer_text extends MIME_Viewer {

    /**
     * Render out the currently set contents in HTML format.
     * The $mime_part class variable has the information to render
     * out, encapsulated in a MIME_Part object.
     */
    function render(&$mime)
    {
        global $conf, $prefs;

        include_once HORDE_BASE . '/lib/Text.php';

        $text = $this->mime_part->getContents();
        if ($text === false) {
            return '<i>' . _("There was an error displaying this message part") . '</i>';
        }

        if (trim($text) == '') {
            return $text;
        }

        $charset = $this->getCharset($mime);
        if ($charset == 'us-ascii') {
            $charset = 'iso-8859-1';
        }

        /* Check for an invalid character set (this code is from
           NLS::checkCharset() in Horde 3.0). */
        ini_set('track_errors', 1);
        @htmlspecialchars('', ENT_COMPAT, $charset);
        if (isset($php_errormsg)) {
            $charset = 'iso-8859-1';
        }
        ini_restore('track_errors');

        $text = str_replace('</A>', '</a>', $text); // make sure that the original message doesn't contain any capital </A> tags, so we can assume we generated them
        $text = str_replace('<A', '<a', $text);     // ditto for open <A> tags
        $text = Text::linkUrls($text, true);
        $text = @preg_replace('|(\[\s+)*([Mm][Aa][Ii][Ll][Tt][Oo]):(\s?)([^\s\?(?(1)\])"<]*)(\??)([^\s"<]*[\w+#?/&=])?|e', "'\\2:\\3<A href=\"' . str_replace('&amp;', '&', IMP::composeLink('\\4\\5\\6')) . '\" onmouseover=\"status=\'' . @htmlspecialchars(addslashes(sprintf(_(\"Compose Message (%s)\"), '\\4')), ENT_QUOTES, $charset) . '\'; return true;\" onmouseout=\"status=\'\';\">\\4\\5\\6</A>'", $text);
        $text = @htmlspecialchars($text, ENT_QUOTES, $charset);
        $text = str_replace('&lt;A href=&quot;', '<a class="fixed" href="', $text);
        $text = str_replace('&quot; target=&quot;_blank&quot;&gt;', '" target="_blank">', $text);
        $text = str_replace('&quot; onmouseover=&quot;', '" onmouseover="', $text);
        $text = str_replace('&quot; onmouseout=&quot;', '" onmouseout="', $text);
        $text = str_replace('&quot;&gt;','">', $text);
        $text = str_replace('\');&quot;&gt;', '\');">', $text);
        $text = str_replace('&lt;/A&gt;', '</a>', $text); // only reconvert capital /A tags - the ones we generated

        // highlight quoted parts of an email
        if ($prefs->getValue('highlight_text')) {
            $text = implode("\r\n", preg_replace('|^(\s*&gt;.+)$|', '<span class="quoted1">\1</span>', explode("\r\n", $text)));
            $indent = 1;
            while (preg_match('|&gt;(\s?&gt;){' . $indent . '}|', $text)) {
                $text = implode("\r\n", preg_replace('|^<span class="quoted' . ((($indent - 1) % 5) + 1) . '">(\s*&gt;(\s?&gt;){' . $indent . '}.+)$|', '<span class="quoted' . (($indent % 5) + 1) . '">\1', explode("\r\n", $text)));
                $indent++;
            }
        }

        // dim signatures
        if ($prefs->getValue('dim_signature')) {
            $parts = preg_split('|(\r\n--\s*\r\n)|', $text, 2, PREG_SPLIT_DELIM_CAPTURE);
            $text = array_shift($parts);
            if (count($parts)) {
                $text .= '<span class="signature">' . $parts[0];
                $text .= preg_replace('|class="[^"]+"|', 'class="signature-fixed"', $parts[1]);
                $text .= '</span>';
            }
        }

        // filter bad language
        if ($prefs->getValue('filtering')) {
            include_once HORDE_BASE . '/lib/Text.php';
            $text = Text::filter($text, $conf['msg']['filtering']['words'],
                                 $conf['msg']['filtering']['replacement']);
        }

        // wordwrap
        $text = str_replace("\t", '        ', $text);
        $text = str_replace('  ', ' &nbsp;', $text);
        $text = str_replace("\n ", "\n&nbsp;", $text);
        if ($text[0] == ' ') {
            $text = '&nbsp;' . substr($text, 1);
        }
        $text = nl2br($text);
        $text = '<p class="fixed">' . $text . '</p>';

        /* If the text is in a different character set, and we're not
           already in a new window, give the user a link to open it in
           a new window with the right character set. */
        if (strtolower($mime->charset) != strtolower($GLOBALS['registry']->getCharset()) &&
            strtolower($mime->charset) != 'us-ascii' &&
            !strstr($_SERVER['PHP_SELF'], 'view.php')) {
            include_once HORDE_BASE . '/lib/SessionCache.php';

            $text = sprintf(_("<p><i>This message was written in a character set other than your own. If it is not displayed correctly, %sclick here</a> to open it in a new window.</i></p>\n"),
                            Horde::link('', sprintf(_("View %s"), $mime->description), null, null, "view('" . VIEW_ATTACH . "', '" . $mime->imap_id . "', '" . SessionCache::putObject($mime) . "'); return false;")) . $text;
        }

        return $text;
    }

    /**
     * Return text/html as the content-type
     * @return string "text/html" constant
     */
    function getType() {
        return 'text/html';
    }

    function getCharset($mime) {
        return !empty($mime->charset) ? $mime->charset : $GLOBALS['registry']->getCharset();
    }
}
