File:  [LON-CAPA] / loncom / xml / lontexconvert.pm
Revision 1.107: download - view: text, annotated - select for diffs
Fri May 27 18:34:07 2011 UTC (12 years, 11 months ago) by raeburn
Branches: MAIN
CVS tags: version_2_10_0, HEAD
- Duplicate declaration.

    1: # The LearningOnline Network with CAPA
    2: # TeX Conversion Module
    3: #
    4: # $Id: lontexconvert.pm,v 1.107 2011/05/27 18:34:07 raeburn Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: # Copyright for TtHfunc and TtMfunc by Ian Hutchinson. 
   29: # TtHfunc and TtMfunc (the "Code") may be compiled and linked into 
   30: # binary executable programs or libraries distributed by the 
   31: # Michigan State University (the "Licensee"), but any binaries so 
   32: # distributed are hereby licensed only for use in the context
   33: # of a program or computational system for which the Licensee is the 
   34: # primary author or distributor, and which performs substantial 
   35: # additional tasks beyond the translation of (La)TeX into HTML.
   36: # The C source of the Code may not be distributed by the Licensee
   37: # to any other parties under any circumstances.
   38: #
   39: 
   40: package Apache::lontexconvert;
   41: 
   42: use strict;
   43: use tth();
   44: use vars qw($errorstring);
   45: #use Apache::lonxml();
   46: use Apache::lonlocal;
   47: use Apache::lonnet;
   48: use lib '/home/httpd/lib/perl/';
   49: use LONCAPA;
   50: use URI::Escape;
   51: use IO::Socket::INET;
   52: 
   53: # ====================================================================== Header
   54: 
   55: sub init_tth {
   56:     my $options=$env{'course.'.$env{'request.course.id'}.'.tthoptions'};
   57:     if ($options =~ /\S/) {
   58: 	$options = ' '.$options;
   59:     } else {
   60: 	undef($options);
   61:     }
   62:     if ($env{'browser.mathml'}) {
   63: 	&tth::ttminit();
   64: 	if ($env{'browser.unicode'}) {
   65: 	    &tth::ttmoptions('-L -u1'.$options);
   66: 	} else {
   67: 	    &tth::ttmoptions('-L -u0'.$options);
   68: 	}
   69:     } else {
   70: 	&tth::tthinit();
   71: 	if ($env{'browser.unicode'}) {
   72: 	    &tth::tthoptions('-L -u1'.$options);
   73: 	} else {
   74: 	    &tth::tthoptions('-L -u0'.$options);
   75: 	}
   76:     }
   77: }
   78: 
   79: # ================================================================== Conversion
   80: 
   81: $Apache::lontexconvert::messedup=0;
   82: 
   83: 
   84: sub convert_real {
   85:     my ($texstring)=@_;
   86:     my ($xmlstring,$errorstring);
   87:     local $SIG{SEGV}=sub { $Apache::lontexconvert::messedup=1; die; };
   88:     local $SIG{ALRM}=sub { 
   89: 	&Apache::lonnet::logthis("ALRM");
   90: 	$xmlstring='['.&mt("TeX unconverted due to errors").']';
   91: 	$Apache::lontexconvert::messedup=1;
   92: 	die &mt("TeX unconverted due to errors");
   93:     };
   94:     &Apache::lonxml::start_alarm();
   95:     if ($env{'browser.mathml'}) {
   96: 	$xmlstring=&tth::ttm($$texstring);
   97: 	$xmlstring=~s/\<math\>/\<math xmlns=\"\&mathns\;\"\>/g;
   98: 	$xmlstring=~s/\<br\>/\<br\/\>/g;
   99: 	$xmlstring=~s/\<p\>/\<p\>\<\/p\>/g;
  100: 	$errorstring.=&tth::ttmerror();
  101:     } else {
  102: 	$xmlstring=&tth::tth($$texstring);
  103: 	$errorstring.=&tth::ttherror();
  104: 	$xmlstring=~s-</font(\s*)>-</font>-g;
  105:     }
  106:     $xmlstring=~s/^\s*\<br clear\=\"all\"/\<br/s;
  107:     $xmlstring=~s/^\s*//;
  108:     $xmlstring=~s/\s*$//;
  109:     #
  110:     # \rightleftharpoons is not converted by tth but maps
  111:     # reasonably well to &#8660;.  If we get many more of these,
  112:     # we're going to need to have a translation sub.
  113:     #
  114:     my $lrharpoon = pack("U", 0x21cc);
  115:     $xmlstring=~s/\\rightleftharpoons/$lrharpoon/g;
  116: 
  117:     &Apache::lonxml::end_alarm();
  118:     return ($xmlstring,$errorstring);
  119: }
  120: 
  121: sub tth_converted {
  122:     my $texstring=shift;
  123:     my $xmlstring='['.&mt('UNDISPLAYABLE').']';
  124:     if ($Apache::lontexconvert::messedup) {
  125: 	return '['.&mt('TeX unconverted due to previous errors').']';
  126:     }
  127:     $$texstring ='\\documentstyle{article}'.$$texstring;
  128: 
  129:     eval(<<'ENDCONV');
  130:     ($xmlstring,$errorstring)=&convert_real($texstring)
  131: ENDCONV
  132:     if ($@) {
  133: 	$errorstring.=&mt("Evaluation Error: ").$@;
  134: 	$Apache::lontexconvert::messedup=1;
  135:     }
  136:     if ($Apache::lontexconvert::messedup || &tth::tthmessedup() || 
  137: 	$errorstring) {
  138: 	&Apache::lonnet::logthis("Trying to kill myself");
  139: 	$Apache::lontexconvert::messedup=1;
  140: 	if (ref($Apache::lonxml::request)) {
  141: 	    $Apache::lonxml::request->child_terminate();
  142: 	} else {
  143: 	    my $request;
  144: 	    eval { $request=Apache->request; };
  145: 	    if (!$request) {
  146: 		eval { $request=Apache2::RequestUtil->request; };
  147: 	    }
  148: 	    if ($request) {
  149: 		$request->child_terminate();
  150: 	    } else {
  151: 		&Apache::lonnet::logthis("Unable to find a request to do child_terminate on");
  152: 	    }
  153: 	}
  154:     }
  155:     return $xmlstring;
  156: }
  157: 
  158: sub clean_out_math_mode {
  159:     my ($texstring)=@_;
  160:     $$texstring=~s/(?<!\\)\$//g;
  161:     $$texstring=~s/\\[\)\(\]\[]//g;
  162:     $$texstring=~s/\\ensuremath//g;
  163:     return '';
  164: }
  165: 
  166: sub displaystyle {
  167:     my ($texstring)=@_;
  168:     #has a $$ or \[ or \displaystyle or eqnarray in it, guessinng it's display mode
  169:     if ($$texstring=~/[^\\]\$\$/ ||
  170:         $$texstring=~/\\\[/ ||
  171:         $$texstring=~/\\displaystyle/ ||
  172:         $$texstring=~/eqnarray/
  173:        ) { return 1; }
  174:     return 0;
  175: }
  176: 
  177: sub jsMath_converted {
  178:     my $texstring=shift;
  179:     my $tag='span';
  180:     if (&displaystyle($texstring)) { $tag='div'; }
  181:     &clean_out_math_mode($texstring);
  182:     return &jsMath_header().
  183: 	'<'.$tag.' class="math">'.$$texstring.'</'.$tag.'>';
  184: }
  185: 
  186: {
  187:     my @jsMath_sent_header;
  188:     sub jsMath_reset {
  189: 	undef(@jsMath_sent_header);
  190:     }
  191:     sub jsMath_push {
  192: 	push(@jsMath_sent_header,0);
  193:     }
  194:     sub jsMath_header {
  195: 	if (!@jsMath_sent_header) {
  196: 	    &Apache::lonnet::logthis("mismatched calls of jsMath_header and jsMath_process");
  197: 	    return '';
  198: 	}
  199: 	return '' if $jsMath_sent_header[-1];
  200: 	$jsMath_sent_header[-1]=1;
  201: 	return
  202:             '<script type="text/javascript">
  203:                      function NoFontMessage () {}
  204:                      jsMath = {Parser: {prototype: {environments: {\'eqnarray*\' :[\'Array\',null,null,\'rcl\',[5/18,5/18],3,\'D\']}}}};
  205:                    </script>'."\n".
  206: 	    '<script type="text/javascript" src="/adm/jsMath/jsMath.js"></script>'."\n";
  207:     }
  208:     sub jsMath_process {
  209: 	my $state = pop(@jsMath_sent_header);
  210: 	return '' if !$state;
  211: 	return "\n".
  212: 	    '<script type="text/javascript">jsMath.Process()</script>'."\n";
  213:     }
  214:     sub jsMath_state {
  215: 	my ($level) = @_;
  216: 	return $jsMath_sent_header[$level];
  217:     }
  218: }
  219: 
  220: sub tex_engine {
  221:     if (exists($env{'form.texengine'})) {
  222: 	if ($env{'form.texengine'} ne '') {
  223:             return $env{'form.texengine'};
  224:         }
  225:     }    
  226:     if ($env{'request.course.id'}
  227: 	&& exists($env{'course.'.$env{'request.course.id'}.'.texengine'})) {
  228: 	return $env{'course.'.$env{'request.course.id'}.'.texengine'};
  229:     }
  230:     if (exists($env{'environment.texengine'})) {
  231: 	return $env{'environment.texengine'};
  232:     }
  233:     return 'tth';
  234: }
  235: 
  236: sub init_math_support {
  237:     my ($inherit_jsmath) = @_;
  238:     &init_tth();
  239:     &Apache::lontexconvert::jsMath_push();
  240:     if (lc(&tex_engine()) eq 'jsmath' ||
  241: 	($inherit_jsmath && &jsMath_state(-2))) {
  242: 	return &Apache::lontexconvert::jsMath_header();
  243:     }
  244:     return;
  245: }
  246: 
  247: sub mimetex_valign {
  248:     my ($esc_texstring)=@_;
  249:     my $valign = 0;
  250:     my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
  251:     my $hostname = &Apache::lonnet::hostname($lonhost);
  252:     my $path = '/cgi-bin/mimetex.cgi?'.$esc_texstring;
  253:     my $socket;
  254:     &Apache::lonxml::start_alarm();
  255:     $socket = IO::Socket::INET->new(PeerAddr => $hostname,
  256:                                     PeerPort => 'http(80)',
  257:                                     Proto    => 'tcp');
  258:     if ($socket) {
  259:         my $headreq = "HEAD $path HTTP/1.0\r\n\r\n";
  260:         print $socket $headreq;
  261:         while (<$socket>) {
  262:             if (/Vertical\-Align\:\s*?([\-\d]+)/) {
  263:                 $valign = $1;
  264:             }
  265:         }
  266:         $socket->close();
  267:     }
  268:     &Apache::lonxml::end_alarm();
  269:     return $valign;
  270: }
  271: 
  272: sub mimetex_converted {
  273:     my $texstring=shift;
  274: 
  275: # Alt-Argument for screen readers
  276:     my $alt_string=$$texstring;
  277:     $alt_string=~s/\"/\'\'/g;
  278: 
  279: # Is this displaystyle?
  280: 
  281:     my $displaystyle=&displaystyle($texstring);
  282: 
  283: # Remove math environment delimiters
  284: 
  285:     &clean_out_math_mode($texstring);
  286: 
  287:     if ($displaystyle) {
  288: 	$$texstring='\\displaystyle \\Large '.$$texstring;
  289:     }
  290:     my $esc_texstring = &uri_escape($$texstring);
  291:     my $valign = &mimetex_valign($esc_texstring);
  292:     my $result='<img src="/cgi-bin/mimetex.cgi?'.$esc_texstring.'" style="vertical-align:'.$valign.'px" alt="'.$alt_string.'" />';
  293:     if ($displaystyle) {
  294: 	$result='<div style="text-align:center">'.$result.'</div>';
  295:     }
  296:     return $result;
  297: }
  298: 
  299: sub converted {
  300:     my ($string,$mode)=@_;
  301:     if ($mode eq '') { $mode = &tex_engine(); }
  302:     if ($mode =~ /tth/i) {
  303: 	return &tth_converted($string);
  304:     } elsif ($mode =~ /jsmath/i) {
  305: 	return &jsMath_converted($string);
  306:     } elsif ($mode =~ /mimetex/i) {
  307: 	return &mimetex_converted($string);
  308:     } elsif ($mode =~ /raw/i) {
  309:         return $$string;
  310:     }
  311:     return &tth_converted($string);
  312: }
  313: 
  314: # ------------------------------------------------------------ Message display
  315: 
  316: sub to_convert {
  317:     my ($string) = @_;
  318:     &init_tth();
  319:     $string=~s/\<br\s*\/?\>/ /gs;
  320: #    $string=~s/\s/ /gs;
  321:     $string=&HTML::Entities::decode($string);
  322:     return &converted(\$string);
  323: }
  324: 
  325: sub smiley {
  326:     my $expression=shift;
  327:     my %smileys=(
  328:     	 '\:\-*\)' => 'face-smile.png',
  329: 		 '8\-\)'  => 'face-cool.png',
  330: 		 '8\-(I|\|)'   => 'face-glasses.png',
  331: 		 '\:\-(I|\|)'   => 'face-plain.png',
  332: 		 '\:\-(o|O|\(\))' => 'face-surprise.png',
  333: 		 ':\-\('  => 'face-sad.png',
  334: 		 '\;\-\)' => 'face-wink.png',
  335: 		 '\:\-(P|p)'  => 'face-raspberry.png',
  336: 		 '\:\-(\\\|\\/)' => 'face-uncertain.png',
  337: 		 '\:\-D'  => 'face-smile-big.png',
  338: 		 '\:\-(C|\@)'  => 'face-angry.png',
  339: 		 '\:(\'|\`)\-*\(' => 'face-crying.png',
  340: 		 '\:\-(X|x|\#)' => 'face-quiet.png',
  341: 		 '\:\-(s|S)' => 'face-uncertain.png',
  342: 		 '\:\-\$' => 'face-embarrassed.png',
  343: 		 '\:\-\*' => 'face-kiss.png',
  344: 		 '\+O\(' => 'face-sick.png',
  345: 		 '(\&lt\;3|\(heart\))' => 'heart.png',
  346: 		 '\(rose\)' => 'rose.png',
  347: 		 '\(pizza\)' => 'food-pizza.png',
  348: 		 '\(cake\)' => 'food-cake.png',
  349: 		 '\(ninja\)' => 'face-ninja.png',
  350: 		 '\(pirate\)' => 'face-pirate.png',
  351: 		 '\((agree|yes)\)' => 'opinion-agree.png',
  352: 		 '\((disagree|nay)\)' => 'opinion-disagree.png',
  353: 		 '(o|O)\-\)' => 'face-angel.png',
  354: 		 );
  355:     my $iconpath=$Apache::lonnet::perlvar{'lonIconsURL'};
  356:     foreach my $smiley (keys(%smileys)) {
  357: 	$expression=~s/$smiley/\<img src="$iconpath\/$smileys{$smiley}" \/\>/gs; 
  358:     }
  359:     return $expression;
  360: }
  361: 
  362: sub msgtexconverted {
  363:     my ($message,$email) = @_;
  364:     $errorstring='';
  365:     my $outmessage='';
  366:     my $tex=0;
  367:     foreach my $fragment (split(/(?:\&lt\;|\<)\/*m\s*(?:\&gt\;|\>)/i,$message)) {
  368: 	if ($tex) {
  369: 	    if ($email) {
  370: 		$outmessage.='</pre><tt>'.&to_convert($fragment).'</tt><pre>';
  371: 		$tex=0;
  372: 	    } else {
  373: 		$outmessage.=&to_convert($fragment);
  374: 		$tex=0;
  375: 	    }
  376: 	} else {
  377:             $outmessage.=&smiley($fragment);
  378: 	    $tex=1;
  379: 	}
  380:     }
  381:     $message=$outmessage; $outmessage=''; $tex=0;
  382:     foreach my $fragment (split(/(?:\&lt\;|\<)\/*algebra\s*(?:\&gt\;|\>)/i,
  383: 				$message)) {
  384: 	if ($tex) {
  385:         my $algebra = &algebra($fragment, 'web', undef, undef, undef, undef, 'tth');
  386: 	    if ($email) {
  387: 		$outmessage.='</pre><tt>'.$algebra.'</tt><pre>';
  388: 		$tex=0;
  389: 	    } else {
  390: 		$outmessage.=$algebra;
  391: 		$tex=0;
  392: 	    }
  393: 	} else {
  394:         $outmessage.=$fragment;
  395: 	    $tex=1;
  396: 	}
  397:     }
  398:     if (wantarray) {
  399: 	return ($outmessage,$errorstring);
  400:     } else {
  401: 	return $outmessage.$errorstring;
  402:     }
  403: }
  404: 
  405: sub algebra {
  406:     use AlgParser;
  407:     my ($string,$target,$style,$parstack,$safeeval,$tth)=@_;
  408:     my $parser = new AlgParserWithImplicitExpand;
  409:     if ($tth eq 'tth') {&init_tth();}
  410:     $string=&prepare_algebra($string);
  411:     my $ret = $parser->parse($string);
  412:     my $result='['.&mt('Algebra unconverted due to previous errors').']';
  413:     if ( ref($ret) ) {
  414: 	#$parser->tostring();
  415: 	$parser->normalize();
  416: 	my $latex=$parser->tolatex();
  417: 	$latex=&postprocess_algebra($latex);
  418: 	if ($style eq 'display') {
  419: 	    $latex='$$'.$latex.'$$x';
  420: 	} else {
  421: 	    # style is 'inline'
  422: 	    $latex='\\ensuremath{'.$latex.'}';
  423: 	}
  424: 	if ($target eq 'web' || $target eq 'analyze') {
  425:             my $display=&Apache::lonxml::get_param('display',$parstack,$safeeval);
  426:             $result = &converted(\$latex,$display);
  427: #	    $result = &converted(\$latex);
  428: 	} else {
  429: 	    $result = $latex;
  430: 	}
  431:     } else {
  432: 	&Apache::lonxml::error($parser->{'htmlerror'});
  433:     }
  434: }
  435: 
  436: sub prepare_algebra {
  437:     my ($string)=@_;
  438: 
  439:     # makes the decision about what is a minus sign easier supposedly
  440:     $string =~ s/(\<\>|\<\=|\>\=[\=\>\<] *)-/$1 zeroplace -/g;
  441: 
  442:     return $string;
  443: }
  444: 
  445: sub postprocess_algebra {
  446:     my ($string)=@_;
  447:     
  448:     # moodle had these and I don't know why, ignoring them for now
  449:     # $string =~s/\\fun/ /g;
  450: 
  451:     # sqrt(3,4) means the 4 root of 3
  452:     $string =~s/\\sqrt{([^,]+),([^\}]+)}/\\sqrt[$2]{$1}/gs;
  453: 
  454:     # log(3,4) means the log base 4 of 3
  455:     $string =~s/\\log\\left\((.+?),(.+?)\\right\)/\\log_{$2}\\left($1\\right)/gs;
  456: 
  457:     # log(3,4) means the log base 4 of 3
  458:     $string =~s/\\((?:sin|cos|tan|sec|csc|cot)(?:h)?)\\left\((.+?),(.+?)\\right\)/\\$1^{$3}\\left($2\\right)/gs;
  459: 
  460:     # int(3,a,b) integral from a to b of 3
  461:     $string =~s/\\int\\left\((.+?),(.+?),(.+?)\\right\)/\\int_{$2}^{$3}\\left($1\\right)/gs;
  462: 
  463:     # int( ... dx) -> ...
  464:     $string =~s/\\int\\left\((.+?)d[a-z]\\right\)/$1/gs;
  465: 
  466:     # 
  467:     $string =~s/\\lim\\left\((.+?),(.+?),(.+?)\\right\)/\\lim_{$2\\to $3}$1/gs;
  468:     return $string;
  469: }
  470: 1;
  471: __END__
  472: 
  473: 
  474: =pod
  475: 
  476: =head1 NAME
  477: 
  478: Apache::lontexconvert;
  479: 
  480: =head1 SYNOPSIS
  481: 
  482: Access to tth/ttm
  483: 
  484: This is part of the LearningOnline Network with CAPA project
  485: described at http://www.lon-capa.org.
  486: 
  487: 
  488: =head1 SUBROUTINES
  489: 
  490: =over
  491: 
  492: =item init_tth()
  493: 
  494: Header
  495: 
  496: =item convert_real()
  497: 
  498:  we need this routine because &converted can get called from inside
  499:  of the safespace (through &xmlparse('<m>stuff</m>') which doesn't
  500:  allow the opcode for alarm, so we need to compile this before we get
  501:  into the safe space since opcode checks only occur at compile time
  502: 
  503: =item tth_converted()
  504: 
  505: 
  506: =item clean_out_math_mode()
  507: 
  508: 
  509: =item displaystyle()
  510: 
  511: 
  512: =item jsMath_converted()
  513: 
  514: 
  515: =item tex_engine()
  516: 
  517: 
  518: =item init_math_support()
  519: 
  520: =item mimetex_valign()
  521: 
  522:  Makes a HEAD call to /cgi-bin/mimetex.cgi via IO:: to retrieve the 
  523:  vertical alignment, before the subsequent call to mimetex_converted()
  524:  which generates the <img> tag and the corresponding image.
  525: 
  526:  Input: 1.  $esc_texstring (escaped TeX to be rendered by mimetex).
  527:  Output: 1. $valign - number of pixels: positive or negative integer 
  528:             which will be included in <img> tag for mimetex image to
  529:             support vertical alignment of image within a line of text.
  530: 
  531:  If a server is running SSL, and Apache rewrite rules are in place 
  532:  to rewrite requests for http to https, modification will most likely 
  533:  be needed for pass through for HEAD requests for /cgi-bin/mimetex.cgi. 
  534: 
  535:  Example rewrite rules which rewrite all http traffic to https, 
  536:  except HEAD requests for /cgi-bin/mimetex.cgi are:
  537: 
  538:  <IfModule mod_rewrite.c>
  539:      RewriteEngine On
  540:      RewriteLogLevel 0
  541: 
  542:      RewriteCond %{HTTPS} off
  543:      RewriteCond %{HTTP:Host} (.*)
  544:      RewriteCond %{REQUEST_METHOD} !HEAD 
  545:      RewriteRule ^/(.*) https://%1/$1 [R=301,L]
  546: 
  547:      RewriteCond %{HTTPS} off
  548:      RewriteCond %{HTTP:Host} (.*)
  549:      RewriteCond %{REQUEST_METHOD} HEAD
  550:      RewriteCond %{REQUEST_URI} !^/cgi-bin/mimetex.cgi
  551:      RewriteRule ^/(.*) https://%1/$1 [R=301,L]
  552:  </IfModule>
  553: 
  554: =item mimetex_converted()
  555: 
  556: 
  557: =item converted()
  558: 
  559: 
  560: =item to_convert()
  561: 
  562: message display
  563: 
  564: =item smiley()
  565: 
  566: ???
  567: 
  568: =item msgtexconverted()
  569: 
  570: =item algebra()
  571: 
  572: =item prepare_algebra()
  573: 
  574: =item postprocess_algebra()
  575: 
  576: =back
  577: 
  578: =cut
  579: 
  580: 
  581: 

FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>