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