1: # The LearningOnline Network with CAPA
2: # TeX Conversion Module
3: #
4: # $Id: lontexconvert.pm,v 1.98.2.1 2011/02/10 20:07:00 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 ⇔. 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 in it, guessinng it's display mode
169: if ($$texstring=~/[^\\]\$\$/ ||
170: $$texstring=~/\\\[/ ||
171: $$texstring=~/\\displaystyle/) { return 1; }
172: return 0;
173: }
174:
175: sub jsMath_converted {
176: my $texstring=shift;
177: my $tag='span';
178: if (&displaystyle($texstring)) { $tag='div'; }
179: &clean_out_math_mode($texstring);
180: return &jsMath_header().
181: '<'.$tag.' class="math">'.$$texstring.'</'.$tag.'>';
182: }
183:
184: {
185: my @jsMath_sent_header;
186: sub jsMath_reset {
187: undef(@jsMath_sent_header);
188: }
189: sub jsMath_push {
190: push(@jsMath_sent_header,0);
191: }
192: sub jsMath_header {
193: if (!@jsMath_sent_header) {
194: &Apache::lonnet::logthis("mismatched calls of jsMath_header and jsMath_process");
195: return '';
196: }
197: return '' if $jsMath_sent_header[-1];
198: $jsMath_sent_header[-1]=1;
199: return
200: '<script type="text/javascript">
201: function NoFontMessage () {}
202: jsMath = {Parser: {prototype: {environments: {\'eqnarray*\' :[\'Array\',null,null,\'rcl\',[5/18,5/18],3,\'D\']}}}};
203: </script>'."\n".
204: '<script type="text/javascript" src="/adm/jsMath/jsMath.js"></script>'."\n";
205: }
206: sub jsMath_process {
207: my $state = pop(@jsMath_sent_header);
208: return '' if !$state;
209: return "\n".
210: '<script type="text/javascript">jsMath.Process()</script>'."\n";
211: }
212: sub jsMath_state {
213: my ($level) = @_;
214: return $jsMath_sent_header[$level];
215: }
216: }
217:
218: sub tex_engine {
219: if (exists($env{'form.texengine'})) {
220: if ($env{'form.texengine'} ne '') {
221: return $env{'form.texengine'};
222: }
223: }
224: if ($env{'request.course.id'}
225: && exists($env{'course.'.$env{'request.course.id'}.'.texengine'})) {
226: return $env{'course.'.$env{'request.course.id'}.'.texengine'};
227: }
228: if (exists($env{'environment.texengine'})) {
229: return $env{'environment.texengine'};
230: }
231: return 'tth';
232: }
233:
234: sub init_math_support {
235: my ($inherit_jsmath) = @_;
236: &init_tth();
237: &Apache::lontexconvert::jsMath_push();
238: if (lc(&tex_engine()) eq 'jsmath' ||
239: ($inherit_jsmath && &jsMath_state(-2))) {
240: return &Apache::lontexconvert::jsMath_header();
241: }
242: return;
243: }
244:
245: sub mimetex_valign {
246: my ($esc_texstring)=@_;
247: my $valign = 0;
248: my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
249: my $hostname = &Apache::lonnet::hostname($lonhost);
250: my $path = '/cgi-bin/mimetex.cgi?'.$esc_texstring;
251: my $socket;
252: &Apache::lonxml::start_alarm();
253: my $socket = IO::Socket::INET->new(PeerAddr => $hostname,
254: PeerPort => 'http(80)',
255: Proto => 'tcp');
256: if ($socket) {
257: my $headreq = "HEAD $path HTTP/1.0\r\n\r\n";
258: print $socket $headreq;
259: while (<$socket>) {
260: if (/Vertical\-Align\:\s*?([\-\d]+)/) {
261: $valign = $1;
262: }
263: }
264: $socket->close();
265: }
266: &Apache::lonxml::end_alarm();
267: return $valign;
268: }
269:
270: sub mimetex_converted {
271: my $texstring=shift;
272:
273: # Alt-Argument for screen readers
274: my $alt_string=$$texstring;
275: $alt_string=~s/\"/\'\'/g;
276:
277: # Is this displaystyle?
278:
279: my $displaystyle=&displaystyle($texstring);
280:
281: # Remove math environment delimiters
282:
283: &clean_out_math_mode($texstring);
284:
285: if ($displaystyle) {
286: $$texstring='\\displaystyle \\Large '.$$texstring;
287: }
288: my $esc_texstring = &uri_escape($$texstring);
289: my $valign = &mimetex_valign($esc_texstring);
290: my $result='<img src="/cgi-bin/mimetex.cgi?'.$esc_texstring.'" style="vertical-align:'.$valign.'px" alt="'.$alt_string.'" />';
291: if ($displaystyle) {
292: $result='<center>'.$result.'</center>';
293: }
294: return $result;
295: }
296:
297: sub converted {
298: my ($string,$mode)=@_;
299: if ($mode eq '') { $mode = &tex_engine(); }
300: if ($mode =~ /tth/i) {
301: return &tth_converted($string);
302: } elsif ($mode =~ /jsmath/i) {
303: return &jsMath_converted($string);
304: } elsif ($mode =~ /mimetex/i) {
305: return &mimetex_converted($string);
306: } elsif ($mode =~ /raw/i) {
307: return $$string;
308: }
309: return &tth_converted($string);
310: }
311:
312: # ------------------------------------------------------------ Message display
313:
314: sub to_convert {
315: my ($string) = @_;
316: $string=~s/\<br\s*\/?\>/ /gs;
317: # $string=~s/\s/ /gs;
318: $string=&HTML::Entities::decode($string);
319: return &converted(\$string);
320: }
321:
322: sub smiley {
323: my $expression=shift;
324: if ($env{'browser.imagesuppress'} eq 'on') { return $expression; }
325: my %smileys=('\:\-\)' => 'smiley',
326: '8\-\)' => 'coolsmile',
327: '8\-(I|\|)' => 'coolindiff',
328: ':\-(I|\|)' => 'neutral',
329: '\:\-(o|O|\(\))' => 'shocked',
330: ':\-\(' => 'frowny',
331: '\;\-\)' => 'wink',
332: '\:\-P' => 'baeh',
333: '\:\-(\\\|\\/)' => 'hrrm',
334: '\:\-D' => 'bigsmile',
335: '\:\-C' => 'angry',
336: '\:(\'|\`)\-\(' => 'cry',
337: '\:\-(X|\#)' => 'lipsrsealed',
338: '\:\-S' => 'huh');
339: my $iconpath=$Apache::lonnet::perlvar{'lonIconsURL'};
340: foreach my $smiley (keys(%smileys)) {
341: $expression=~s/$smiley/\<img src="$iconpath\/$smileys{$smiley}.gif" \/\>/gs;
342: }
343: return $expression;
344: }
345:
346: sub msgtexconverted {
347: my ($message,$email) = @_;
348: $errorstring='';
349: &init_tth();
350: my $outmessage='';
351: my $tex=0;
352: foreach my $fragment (split(/(?:\<\;|\<)\/*m\s*(?:\>\;|\>)/i,$message)) {
353: if ($tex) {
354: if ($email) {
355: $outmessage.='</pre><tt>'.&to_convert($fragment).'</tt><pre>';
356: $tex=0;
357: } else {
358: $outmessage.=&to_convert($fragment);
359: $tex=0;
360: }
361: } else {
362: $outmessage.=&smiley($fragment);
363: $tex=1;
364: }
365: }
366: $message=$outmessage; $outmessage=''; $tex=0;
367: foreach my $fragment (split(/(?:\<\;|\<)\/*algebra\s*(?:\>\;|\>)/i,
368: $message)) {
369: if ($tex) {
370: if ($email) {
371: $outmessage.='</pre><tt>'.&algebra($fragment,'web').'</tt><pre>';
372: $tex=0;
373: } else {
374: $outmessage.=&algebra($fragment,'web');
375: $tex=0;
376: }
377: } else {
378: $outmessage.=$fragment;
379: $tex=1;
380: }
381: }
382: if (wantarray) {
383: return ($outmessage,$errorstring);
384: } else {
385: return $outmessage.$errorstring;
386: }
387: }
388:
389: sub algebra {
390: use AlgParser;
391:
392: my ($string,$target,$style,$parstack,$safeeval)=@_;
393: my $parser = new AlgParserWithImplicitExpand;
394: $string=&prepare_algebra($string);
395: my $ret = $parser->parse($string);
396: my $result='['.&mt('Algebra unconverted due to previous errors').']';
397: if ( ref($ret) ) {
398: #$parser->tostring();
399: $parser->normalize();
400: my $latex=$parser->tolatex();
401: $latex=&postprocess_algebra($latex);
402: if ($style eq 'display') {
403: $latex='$$'.$latex.'$$x';
404: } else {
405: # style is 'inline'
406: $latex='\\ensuremath{'.$latex.'}';
407: }
408: if ($target eq 'web' || $target eq 'analyze') {
409: my $display=&Apache::lonxml::get_param('display',$parstack,$safeeval);
410: $result = &converted(\$latex,$display);
411: # $result = &converted(\$latex);
412: } else {
413: $result = $latex;
414: }
415: } else {
416: &Apache::lonxml::error($parser->{'htmlerror'});
417: }
418: }
419:
420: sub prepare_algebra {
421: my ($string)=@_;
422:
423: # makes the decision about what is a minus sign easier supposedly
424: $string =~ s/(\<\>|\<\=|\>\=[\=\>\<] *)-/$1 zeroplace -/g;
425:
426: return $string;
427: }
428:
429: sub postprocess_algebra {
430: my ($string)=@_;
431:
432: # moodle had these and I don't know why, ignoring them for now
433: # $string =~s/\\fun/ /g;
434:
435: # sqrt(3,4) means the 4 root of 3
436: $string =~s/\\sqrt{([^,]+),([^\}]+)}/\\sqrt[$2]{$1}/gs;
437:
438: # log(3,4) means the log base 4 of 3
439: $string =~s/\\log\\left\((.+?),(.+?)\\right\)/\\log_{$2}\\left($1\\right)/gs;
440:
441: # log(3,4) means the log base 4 of 3
442: $string =~s/\\((?:sin|cos|tan|sec|csc|cot)(?:h)?)\\left\((.+?),(.+?)\\right\)/\\$1^{$3}\\left($2\\right)/gs;
443:
444: # int(3,a,b) integral from a to b of 3
445: $string =~s/\\int\\left\((.+?),(.+?),(.+?)\\right\)/\\int_{$2}^{$3}\\left($1\\right)/gs;
446:
447: # int( ... dx) -> ...
448: $string =~s/\\int\\left\((.+?)d[a-z]\\right\)/$1/gs;
449:
450: #
451: $string =~s/\\lim\\left\((.+?),(.+?),(.+?)\\right\)/\\lim_{$2\\to $3}$1/gs;
452: return $string;
453: }
454: 1;
455: __END__
456:
457:
458: =pod
459:
460: =head1 NAME
461:
462: Apache::lontexconvert;
463:
464: =head1 SYNOPSIS
465:
466: Access to tth/ttm
467:
468: This is part of the LearningOnline Network with CAPA project
469: described at http://www.lon-capa.org.
470:
471:
472: =head1 SUBROUTINES
473:
474: =over
475:
476: =item init_tth()
477:
478: Header
479:
480: =item convert_real()
481:
482: we need this routine because &converted can get called from inside
483: of the safespace (through &xmlparse('<m>stuff</m>') which doesn't
484: allow the opcode for alarm, so we need to compile this before we get
485: into the safe space since opcode checks only occur at compile time
486:
487: =item tth_converted()
488:
489:
490: =item clean_out_math_mode()
491:
492:
493: =item displaystyle()
494:
495:
496: =item jsMath_converted()
497:
498:
499: =item tex_engine()
500:
501:
502: =item init_math_support()
503:
504: =item mimetex_valign()
505:
506: Makes a HEAD call to /cgi-bin/mimetex.cgi via IO:: to retrieve the
507: vertical alignment, before the subsequent call to mimetex_converted()
508: which generates the <img> tag and the corresponding image.
509:
510: Input: 1. $esc_texstring (escaped TeX to be rendered by mimetex).
511: Output: 1. $valign - number of pixels: positive or negative integer
512: which will be included in <img> tag for mimetex image to
513: support vertical alignment of image within a line of text.
514:
515: If a server is running SSL, and Apache rewrite rules are in place
516: to rewrite requests for http to https, modification will most likely
517: be needed for pass through for HEAD requests for /cgi-bin/mimetex.cgi.
518:
519: Example rewrite rules which rewrite all http traffic to https,
520: except HEAD requests for /cgi-bin/mimetex.cgi are:
521:
522: <IfModule mod_rewrite.c>
523: RewriteEngine On
524: RewriteLogLevel 0
525:
526: RewriteCond %{HTTPS} off
527: RewriteCond %{HTTP:Host} (.*)
528: RewriteCond %{REQUEST_METHOD} !HEAD
529: RewriteRule ^/(.*) https://%1/$1 [R=301,L]
530:
531: RewriteCond %{HTTPS} off
532: RewriteCond %{HTTP:Host} (.*)
533: RewriteCond %{REQUEST_METHOD} HEAD
534: RewriteCond %{REQUEST_URI} !^/cgi-bin/mimetex.cgi
535: RewriteRule ^/(.*) https://%1/$1 [R=301,L]
536: </IfModule>
537:
538: =item mimetex_converted()
539:
540:
541: =item converted()
542:
543:
544: =item to_convert()
545:
546: message display
547:
548: =item smiley()
549:
550: ???
551:
552: =item msgtexconverted()
553:
554: =item algebra()
555:
556: =item prepare_algebra()
557:
558: =item postprocess_algebra()
559:
560: =back
561:
562: =cut
563:
564:
565:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>