[system] / trunk / pg / macros / dangerousMacros.pl Repository:
ViewVC logotype

View of /trunk/pg/macros/dangerousMacros.pl

Parent Directory Parent Directory | Revision Log Revision Log


Revision 3359 - (download) (as text) (annotate)
Tue Jul 5 21:58:51 2005 UTC (14 years, 7 months ago) by sh002i
File size: 49890 byte(s)
chech tthPreamble path and mtime to deal with changes to the file
between runs. this is necessary now that dangerousMacros.pl is cached.
Closes bug #798.

    1 
    2 
    3 
    4 ####################################################################
    5 # Copyright @ 1995-1999 University of Rochester
    6 # All Rights Reserved
    7 ####################################################################
    8 
    9 ####################################################################
   10 #
   11 #  dangerousMacros.pl contains macros with potentially dangerous commands
   12 #  such as require and eval.  They can reference disk files for reading and
   13 #  writing and can create links.  It may be necessary to modify certain addresses
   14 #  in this file to make the scripts run in different environments.
   15 #
   16 #
   17 
   18 =head1 NAME
   19 
   20    dangerousMacros.pl --- located in the courseScripts directory
   21 
   22 =head1 SYNPOSIS
   23 
   24   loadMacros(macrofile1,macrofile2,...)
   25 
   26   insertGraph(graphObject);
   27     returns a path to the file containing the graph image.
   28 
   29   tth(texString)
   30     returns an HTML version of the tex code passed to it.
   31 
   32   alias(pathToFile);
   33     returns URL which links to that file
   34 
   35 
   36 =head1 DESCRIPTION
   37 
   38 
   39 C<dangerousMacros.pl> contains macros with potentially dangerous commands
   40 such as require and eval.  They can reference disk files for reading and
   41 writing and can create links.  It may be necessary to modify certain addresses
   42 in this file to make the scripts run properly in different environments.
   43 
   44 C<dangerousMacros.pl> is loaded and reinitialized
   45 every time a new problem is rendered.
   46 
   47 =cut
   48 
   49 
   50 ######## Dangerous macros#########
   51 ## The macros in this file are defined while the safe compartment is wide open.
   52 ## Be careful!
   53 #########################################
   54 
   55 
   56 =head2 Sharing modules:
   57 
   58 Most modules are loaded by dangerousMacros.pl
   59 
   60 The modules must be loaded using require (not use) since the courseScriptsDirectory is
   61 defined at run time.
   62 
   63 
   64  The following considerations come into play.
   65 
   66   * One needs to limit the access to modules for safety -- hence only
   67    modules in the F<courseScriptsDirectory> can be loaded.
   68 
   69   * Loading them in dangerousMacros.pl is wasteful, since the modules
   70    would need to be reloaded everytime a new safe compartment is created.
   71      (I believe that using require takes care of this.)
   72 
   73   * Loading GD within a safeCompartment creates infinite recurrsion in AUTOLOAD (probably a bug)
   74    hence this module is loaded by translate.pl and then shared with
   75    the safe compartment.
   76 
   77   * Other modules loaded by translate.pl are C<Exporter> and C<DynaLoader.
   78 
   79   * PGrandom is loaded by F<PG.pl> , since it is needed there.
   80 
   81 
   82 
   83 The module name spaces loaded in dangerousMacros are:
   84 
   85   PGrandom (if not previously loaded)
   86   WWPlot
   87   Fun
   88   Label
   89   Circle
   90 
   91 in addition the  subroutine &evaluate_units is shared from the module Units.
   92 
   93 =cut
   94 
   95 BEGIN {
   96   be_strict(); # an alias for use strict.  This means that all global variable must contain main:: as a prefix.
   97 
   98 }
   99 
  100 my $debugON = 0;
  101 
  102 # grab read only variables from the current safe compartment
  103 
  104 my ($macrosPath,
  105     $pwd,
  106   $templateDirectory,
  107   $scriptDirectory,
  108   $externalTTHPath,
  109   );
  110 
  111 sub _dangerousMacros_init {   #use  envir instead of local variables?
  112     $macrosPath               = eval('$main::envir{macrosPath}');
  113     $pwd                      = eval('$main::envir{fileName}'); $pwd =~ s!/[^/]*$!!;
  114     $templateDirectory        = eval('$main::envir{templateDirectory}');
  115     $scriptDirectory          = eval('$main::envir{scriptDirectory}');
  116     $externalTTHPath          = eval('$main::envir{externalTTHPath}');
  117     warn "dangerousmacros initialized" if $debugON;
  118     warn eval(q! "dangerousmacros.pl externalTTHPath is ".$main::externalTTHPath;!) if $debugON;
  119     warn eval(q! "dangerousmacros.pl:  The envir variable $main::{envir} is".join(" ",%main::envir)!) if $debugON;
  120 }
  121 
  122 sub _dangerousMacros_export {
  123   my @EXPORT= (
  124       '&_dangerousMacros_init',
  125     '&alias',
  126     '&compile_file',
  127     '&insertGraph',
  128     '&loadMacros',
  129     '&HEADER_TEXT',
  130     '&sourceAlias',
  131     '&tth',
  132   );
  133   @EXPORT;
  134 }
  135 
  136 
  137 =head2 loadMacros
  138 
  139 C<loadMacros(macrofile1,macrofile2,...)>
  140 
  141 loadMacros takes a list of file names and evaluates the contents of each file.  This is used to load macros
  142 which define and augment the PG language.  The macro files are searched for in the directories specified by
  143 C<($macrosPath)>, which by default is the course macros directory followed by WeBWorK's pg/macros directory.
  144 The latter is where the default behaviour of the PG language is defined.  The default path is set in
  145 the C<(global.conf)> file.
  146 
  147 An individual course can modify the PG language, B<for that course only>, by
  148 duplicating one of the macro files in the courseScripts directory and placing this
  149 file in the macro directory for the course. The new file in the course
  150 macro directory will now be used instead of the file in the courseScripts directory.
  151 
  152 The new file in the course macro directory can by modified by adding macros or modifying existing macros.
  153 
  154 I< Modifying macros is for users with some experience.>
  155 
  156 Modifying existing macros might break other standard macros or problems which depend on the
  157 unmodified behavior of these macors so do this with great caution.
  158 In addition problems which use new macros defined in these files or which depend on the
  159 modified behavior of existing macros will not work in other courses unless the macros are also
  160 transferred to the new course.  It helps to document the  problems by indicating any special macros
  161 which the problems require.
  162 
  163 There is no facility for modifying or overloading a single macro.  The entire file containing the macro
  164 must be overloaded.
  165 
  166 Modifications to files in the course macros directory affect only that course,
  167 they will not interfere with the normal behavior of B<WeBWorK> in other courses.
  168 
  169 
  170 
  171 =cut
  172 
  173 # Global variables used
  174 #   ${main::macrosPath}
  175 # Global macros used
  176 # None
  177 
  178 # Because of the need to use the directory variables it is tricky to define this
  179 # in translate.pl since, as currently written, the directories are not available
  180 # at that time.  Perhaps if I rewrite translate as an object that method will work.
  181 
  182 # The only difficulty with defining loadMacros inside the Safe compartment is that
  183 # the error reporting does not work with syntax errors.
  184 # A kludge using require works around this problem
  185 
  186 
  187 
  188 sub loadMacros {
  189     my @files = @_;
  190     my $fileName;
  191     eval {main::time_it("begin load macros");};
  192     ###############################################################################
  193   # At this point the directories have been defined from %envir and we can define
  194   # the directories for this file
  195   ###############################################################################
  196 
  197   # special case inits
  198   foreach my $file ('PG.pl','dangerousMacros.pl','IO.pl') {
  199       my $macro_file_name = $file;
  200     $macro_file_name =~s/\.pl//;  # trim off the extension
  201     $macro_file_name =~s/\.pg//;  # sometimes the extension is .pg (e.g. CAPA files)
  202     my $init_subroutine_name = "_${macro_file_name}_init";
  203       my $init_subroutine  = eval { \&{$init_subroutine_name} };
  204     use strict;
  205         my $macro_file_loaded = defined($init_subroutine);
  206         warn "dangerousMacros: macro init $init_subroutine_name defined |$init_subroutine| |$macro_file_loaded|" if $debugON;
  207     if ( defined($init_subroutine) && defined( &{$init_subroutine} ) ) {
  208 
  209         warn "dangerousMacros:  initializing $macro_file_name"  if $debugON;
  210         &$init_subroutine();
  211     }
  212   }
  213     unless (defined( $externalTTHPath)){
  214       warn "WARNING::Please make sure that the DOCUMENT() statement comes before<BR>\n" .
  215            " the loadMacros() statement in the problem template.<p>" .
  216            " The externalTTHPath variable |$externalTTHPath| was\n".
  217            " not defined which usually indicates the problem above.<br>\n";
  218 
  219     }
  220     #warn "running load macros";
  221     while (@files) {
  222         $fileName = shift @files;
  223         next  if ($fileName =~ /^PG.pl$/) ;    # the PG.pl macro package is already loaded.
  224 
  225         my $macro_file_name = $fileName;
  226     $macro_file_name =~s/\.pl//;  # trim off the extension
  227     $macro_file_name =~s/\.pg//;  # sometimes the extension is .pg (e.g. CAPA files)
  228     my $init_subroutine_name = "_${macro_file_name}_init";
  229     $init_subroutine_name =~ s![^a-zA-Z0-9_]!_!g;  # remove dangerous chars
  230 
  231     ###############################################################################
  232     # For some reason the "no stict" which works on webwork-db doesn't work on
  233     # webwork.  For this reason the constuction &{$init_subroutine_name}
  234     # was abandoned and replaced by eval.  This is considerably more dangerous
  235     # since one could hide something nasty in a file name.
  236     #  Keep an eye on this ???
  237     # webwork-db used perl 5.6.1 and webwork used perl 5.6.0
  238     ###############################################################################
  239 
  240     # compile initialization subroutine. (5.6.0 version)
  241 
  242 
  243 #   eval( q{ \$init_subroutine = \\&main::}.$init_subroutine_name);
  244 #   warn "dangerousMacros: failed to compile $init_subroutine_name. $@" if $@;
  245 
  246 
  247     ###############################################################################
  248     #compile initialization subroutine. (5.6.1 version) also works with 5.6.0
  249 
  250 #     no strict;
  251     my $init_subroutine  = eval { \&{'main::'.$init_subroutine_name} };
  252 #     use strict;
  253 
  254     ###############################################################################
  255         # macros are searched for in the directories listed in the $macrosPath array reference.
  256 
  257         my $macro_file_loaded = defined($init_subroutine) && defined(&$init_subroutine);
  258         warn "dangerousMacros: macro init $init_subroutine_name defined |$init_subroutine| |$macro_file_loaded|"  if $debugON;
  259         unless ($macro_file_loaded) {
  260           warn "loadMacros: loading macro file $fileName\n" if $debugON;
  261     my $filePath = findMacroFile($fileName);
  262     #### (check for renamed files here?) ####
  263     if ($filePath) {compile_file($filePath)}
  264     else {
  265       die "Can't locate macro file |$fileName| via path: |".join("|, |",@{$macrosPath})."|";
  266     }
  267     }
  268     ###############################################################################
  269     # Try again to define the initialization subroutine. (5.6.0 version)
  270 
  271 #   eval( q{ \$init_subroutine = \\&main::}.$init_subroutine_name );
  272 #   warn "dangerousMacros: failed to compile $init_subroutine_name. $@" if $@;
  273 #   $init_subroutine = $temp::rf_init_subroutine;
  274     ###############################################################################
  275     # Try again to define the initialization subroutine. (5.6.1 version) also works with 5.6.0
  276 
  277 #     no strict;
  278     $init_subroutine  = eval { \&{'main::'.$init_subroutine_name} };
  279 #     use strict;
  280     ###############################################################################
  281     #warn "loadMacros: defining \$temp::rf_init_subroutine ",$temp::rf_init_subroutine;
  282        $macro_file_loaded = defined($init_subroutine) && defined(&$init_subroutine);
  283        warn "dangerousMacros: macro init $init_subroutine_name defined |$init_subroutine| |$macro_file_loaded|" if $debugON;
  284 
  285     if ( defined($init_subroutine) && defined( &{$init_subroutine} ) ) {
  286 
  287         warn "dangerousMacros:  initializing $macro_file_name" if $debugON;
  288         &$init_subroutine();
  289     }
  290     #warn "main:: contains <br>\n $macro_file_name ".join("<br>\n $macro_file_name ", %main::);
  291 
  292   }
  293   eval{main::time_it("end load macros");};
  294 }
  295 
  296 #
  297 #  Look for a macro file in the directories specified in the macros path
  298 #
  299 sub findMacroFile {
  300   my $fileName = shift;
  301   my $filePath;
  302   foreach my $dir (@{$macrosPath}) {
  303     $filePath = "$dir/$fileName";
  304     $filePath =~ s!^\.\.?/!$templateDirectory$pwd/!;
  305     return $filePath if (-r $filePath);
  306   }
  307   return;  # no file found
  308 }
  309 
  310 # errors in compiling macros is not always being reported.
  311 sub compile_file {
  312   my $filePath = shift;
  313   warn "loading $filePath" if $debugON;
  314   local(*MACROFILE);
  315   local($/);
  316   $/ = undef;   # allows us to treat the file as a single line
  317   open(MACROFILE, "<$filePath") || die "Cannot open file: $filePath";
  318   my $string = 'BEGIN {push @__eval__, __FILE__}; ' . <MACROFILE>;
  319   my ($result,$error,$fullerror) = &PG_restricted_eval($string);
  320   eval ('$main::__files__->{pop @main::__eval__} = $filePath');
  321   if ($error) {    # the $fullerror report has formatting and is never empty
  322                 # this is now handled by PG_errorMessage() in the PG translator
  323     #$fullerror =~ s/\(eval \d+\)/ $filePath\n/;   # attempt to insert file name instead of eval number
  324     die "Error detected while loading $filePath:\n$fullerror";
  325 
  326   }
  327 
  328   close(MACROFILE);
  329 
  330 }
  331 
  332 # This creates on the fly graphs
  333 
  334 =head2 insertGraph
  335 
  336   $filePath = insertGraph(graphObject);
  337       returns a path to the file containing the graph image.
  338 
  339 insertGraph(graphObject) writes a gif file to the C<html/tmp/gif> directory of the current course.
  340 The file name
  341 is obtained from the graphObject.  Warnings are issued if errors occur while writing to
  342 the file.
  343 
  344 The permissions and ownership of the file are controlled by C<$main::tmp_file_permission>
  345 and C<$main::numericalGroupID>.
  346 
  347 B<Returns:>   A string containing the full path to the temporary file containing the GIF image.
  348 
  349 
  350 
  351 InsertGraph draws the object $graph, stores it in "${tempDirectory}gif/$gifName.gif (or .png)" where
  352 the $imageName is obtained from the graph object.  ConvertPath and surePathToTmpFile are used to insure
  353 that the correct directory separators are used for the platform and that the necessary directories
  354 are created if they are not already present.
  355 
  356 The directory address to the file is the result.  This is most often used in the construct
  357 
  358   TEXT(alias(insertGraph($graph)) );
  359 
  360 where alias converts the directory address to a URL when serving HTML pages and insures that
  361 an eps file is generated when creating TeX code for downloading.
  362 
  363 =cut
  364 
  365 # Global variables used:
  366 # $main::tmp_file_permission,
  367 # $main::numericalGroupID
  368 
  369 #Global macros used:
  370 #   &convertPath
  371 #   &surePathToTmpFile
  372 
  373 sub insertGraph {
  374         # Convert the image to GIF and print it on standard output
  375   my $graph = shift;
  376   my $extension = ($WWPlot::use_png) ? '.png' : '.gif';
  377   my $fileName = $graph->imageName  . $extension;
  378   my $filePath = convertPath("gif/$fileName");
  379   $filePath = &surePathToTmpFile( $filePath );
  380   # Check to see if we already have this graph, or if we have to make it
  381   if( not -e $filePath # does it exist?
  382     or ((stat "$templateDirectory"."$main::envir{fileName}")[9] > (stat $filePath)[9]) # source has changed
  383           or $graph->imageName =~ /Undefined_Set/) { # problems from SetMaker and its ilk should always be redone
  384     #createFile($filePath, $main::tmp_file_permission, $main::numericalGroupID);
  385     local(*OUTPUT);  # create local file handle so it won't overwrite other open files.
  386     open(OUTPUT, ">$filePath")||warn ("$0","Can't open $filePath<BR>","");
  387     chmod( 0777, $filePath);
  388     print OUTPUT $graph->draw|| warn("$0","Can't print graph to $filePath<BR>","");
  389     close(OUTPUT)||warn("$0","Can't close $filePath<BR>","");
  390   }
  391   $filePath;
  392 }
  393 
  394 
  395 
  396 =head2 tth
  397 
  398   tth(texString)
  399       returns an HTML version of the tex code passed to it.
  400 
  401 This macro sends the texString to the filter program C<tth> created by Ian Hutchinson.
  402 The tth program was created by Ian Hutchinson and is freely available
  403 for B<non-commerical purposes> at the C<tth> main site: C<http://hutchinson.belmont.ma.us/tth/>.
  404 
  405 The purpose of C<tth> is to translate text in the TeX or Latex markup language into
  406 HTML markup as best as possible.  Some symbols, such as square root symbols are not
  407 translated completely.  Macintosh users must use the "MacRoman" encoding (available in 4.0 and
  408 higher browsers) in order to view the symbols correctly.  WeBWorK attempts to force Macintosh
  409 browsers to use this encoding when such a browser is detected.
  410 
  411 The contents of the file C<tthPreamble.tex> in the courses template directory are prepended
  412 to each string.  This allows one to define TeX macros which can be used in every problem.
  413 Currently there is no default C<tthPreamble.tex> file, so if the file is not present in the
  414 course template directory no TeX macro definitions are prepended.  C<tth> already understands most
  415 Latex commands, but will not, in general know I<AMS-Latex> commands.  Additional information
  416 on C<tth> is available at the C<tth> main site.
  417 
  418 This macro contains code which is system dependent and may need to be modified
  419 to run on different systems.
  420 
  421 =for html
  422 The link to <CODE>tth</CODE> for <STRONG>non-commerical</STRONG> is
  423 <A HREF="http://hutchinson.belmont.ma.us/tth/">http://hutchinson.belmont.ma.us/tth/</A>.
  424 Binaries for many operating systems are available as well as the source code.  Links
  425 describing how to obtain <CODE>tth</CODE> for commerical use are also available on this page.
  426 
  427 =cut
  428 
  429 
  430 
  431 # This file allows the tth display.
  432 # Global variables:
  433 # ${main::templateDirectory}tthPreamble.tex   # location of any preamble TeX commands for tth
  434 #   ${main::templateDirectory}
  435 #   ${main::scriptDirectory}tth        # path to tth application
  436 # Global macros:
  437 #   None
  438 
  439 # the contents of this file will not change during problem compilation it
  440 # only needs to be read once. however, the contents of the file may change,
  441 # and indeed the file refered to may change, between rendering passes. thus,
  442 # we need to keep track of the file name and the mtime as well.
  443 my ($tthPreambleFile, $tthPreambleMtime, $tthPreambleContents);
  444 
  445 sub tth {
  446   my $inputString = shift;
  447 
  448   my $thisFile = "${templateDirectory}tthPreamble.tex" if -r "${templateDirectory}tthPreamble.tex";
  449 
  450   if (defined $thisFile) {
  451     my $thisMtime = (stat $thisFile)[9];
  452     my $load =
  453       # load preamble if we haven't loaded it ever
  454       (not defined $tthPreambleFile or not defined $tthPreambleMtime or not defined $tthPreambleContents)
  455         ||
  456       # load if the file path has changed
  457       ($tthPreambleFile ne $thisFile)
  458         ||
  459       # load if the file has been modified
  460       ($tthPreambleMtime < $thisMtime);
  461 
  462     if ($load) {
  463       local(*TTHIN);
  464       open (TTHIN, "${templateDirectory}tthPreamble.tex") || die "Can't open file ${templateDirectory}tthPreamble.tex";
  465       local($/);
  466       $/ = undef;
  467       $tthPreambleContents = <TTHIN>;
  468       close(TTHIN);
  469 
  470       $tthPreambleContents =~ s/(.)\n/$1%\n/g;  # thanks to Jim Martino
  471                                                 # each line in the definition file
  472                                                 # should end with a % to prevent
  473                                                 # adding supurious paragraphs to output.
  474 
  475       $tthPreambleContents .="%\n";             # solves the problem if the file doesn't end with a return.
  476     }
  477   } else {
  478     $tthPreambleContents = "";
  479   }
  480 
  481     $inputString = $tthPreambleContents . $inputString;
  482     $inputString    = "<<END_OF_TTH_INPUT_STRING;\n\n\n" . $inputString . "\nEND_OF_TTH_INPUT_STRING\necho \"\" >/dev/null"; #it's not clear why another command is needed.
  483 
  484   # $tthpath is now taken from $Global::externalTTHPath via %envir.
  485     my $tthpath     = $envir{externalTTHPath};
  486     my $out;
  487 
  488     if (-x $tthpath ) {
  489       my $tthcmd      = "$tthpath -L -f5 -u -r  2>/dev/null " . $inputString;
  490       if (open(TTH, "$tthcmd   |")) {
  491           local($/);
  492       $/ = undef;
  493       $out = <TTH>;
  494       $/ = "\n";
  495       close(TTH);
  496       }else {
  497           $out = "<BR>there has been an error in executing $tthcmd<BR>";
  498       }
  499   } else {
  500     $out = "<BR> Can't execute the program tth at |$tthpath|<BR>";
  501     }
  502 
  503     $out;
  504 }
  505 
  506 # possible solution to the tth font problem?  Works only for iCab.
  507 sub symbolConvert {
  508   my  $string = shift;
  509   $string =~ s/\x5C/\&#092;/g;    #\      92                       &#092;
  510   $string =~ s/\x7B/\&#123;/g;    #{      123                       &#123;
  511   $string =~ s/\x7D/\&#125;/g;    #}      125                       &#125;
  512   $string =~ s/\xE7/\&#193;/g;    #      231                       &#193;
  513   $string =~ s/\xE6/\&#202;/g;    #      230                       &#202;
  514   $string =~ s/\xE8/\&#203;/g;    #      232                       &#203;
  515   $string =~ s/\xF3/\&#219;/g;    #      243                       &#219;
  516   $string =~ s/\xA5/\&bull;/g;    #      165                       &bull;
  517   $string =~ s/\xB2/\&le;/g;      #      178                       &le;
  518   $string =~ s/\xB3/\&ge;/g;      #      179                       &ge;
  519   $string =~ s/\xB6/\&part;/g;    #      182                       &part;
  520   $string =~ s/\xCE/\&#338;/g;    #      206                       &#338;
  521   $string =~ s/\xD6/\&#732/g;     #      214                       &#732;
  522   $string =~ s/\xD9/\&Yuml;/g;    #      217                       &Yuml;
  523   $string =~ s/\xDA/\&frasl;/g;   #      218                       &frasl;
  524   $string =~ s/\xF5/\&#305;/g;    #      245                       &#305
  525   $string =~ s/\xF6/\&#710;/g;    #      246                       &#710;
  526   $string =~ s/\xF7/\&#193;/g;    #      247                       &#193;
  527   $string =~ s/\xF8/\&#175;/g;    #      248                       &#175;
  528   $string =~ s/\xF9/\&#728;/g;    #      249                       &#728;
  529   $string =~ s/\xFA/\&#729;/g;    #      250                       &#729;
  530   $string =~ s/\xFB/\&#730;;/g;   #      251                       &#730;
  531   $string;
  532 }
  533 
  534 # ----- ----- ----- -----
  535 
  536 =head2 math2img
  537 
  538 math2img(texString) - returns an IMG tag pointing to an image version of the supplied TeX
  539 
  540 =cut
  541 
  542 my $math2imgCount = 0;
  543 
  544 sub math2img {
  545   my $tex = shift;
  546   my $mode = shift;
  547 
  548   my $sourcePath = $envir{templateDirectory} . "/" . $envir{fileName};
  549   my $tempFile = "m2i/$envir{studentLogin}.$envir{setNumber}.$envir{probNum}."
  550     . $math2imgCount++ . ".png";
  551   my $tempPath = surePathToTmpFile($tempFile); #my $tempPath = "$envir{tempDirectory}$tempFile";
  552   my $tempURL = "$envir{tempURL}/$tempFile";
  553   my $forceRefresh = $envir{refreshMath2img};
  554   my $imageMissing = not -e $tempPath;
  555   my $imageStale   = (stat $sourcePath)[9] > (stat $tempPath)[9] if -e $tempPath;
  556   if ($forceRefresh or $imageMissing or $imageStale) {
  557     # image file doesn't exist, or source file is newer then image file
  558     #warn "math2img: refreshMath2img forcing image generation for $tempFile\n" if $forceRefresh;
  559     #warn "math2img: $tempFile doesn't exist, so generating it\n" if $imageMissing;
  560     #warn "math2img: source file (", (stat $sourcePath)[9], ") is newer than image file (",
  561     # (stat $tempPath)[9], ") so re-generating image\n" if $imageStale;
  562     if (-e $tempPath) {
  563       unlink $tempPath or die "Failed to delete stale math2img file $tempPath: $!";
  564     }
  565     dvipng(
  566       $envir{dvipngTempDir}, $envir{externalLaTeXPath},
  567       $envir{externalDvipngPath}, $tex, $tempPath
  568     );
  569   }
  570 
  571   if (-e $tempPath) {
  572     return "<img align=\"middle\" src=\"$tempURL\" alt=\"$tex\">"            if $mode eq "inline";
  573     return "<div align=\"center\"><img src=\"$tempURL\" alt=\"$tex\"></div>" if $mode eq "display";
  574   } else {
  575     return "<b>[math2img failed]</b>";
  576     # it might be nice to call tth here as a fallback instead:
  577     #return tth($tex);
  578   }
  579 };
  580 
  581 
  582 # copied from IO.pm for backward compatibility with WeBWorK1.8;
  583 sub dvipng($$$$$) {
  584   my (
  585     $wd,        # working directory, for latex and dvipng garbage
  586                 # (must already exist!)
  587     $latex,     # path to latex binary
  588     $dvipng,    # path to dvipng binary
  589     $tex,       # tex string representing equation
  590     $targetPath # location of resulting image file
  591   ) = @_;
  592 
  593   my $dvipngBroken = 0;
  594 
  595   my $texFile  = "$wd/equation.tex";
  596   my $dviFile  = "$wd/equation.dvi";
  597   my $dviFile2 = "$wd/equationequation.dvi";
  598   my $dviCall  = "equation";
  599   my $pngFile  = "$wd/equation1.png";
  600 
  601   unless (-e $wd) {
  602     die "dvipng working directory $wd doesn't exist -- caller should have created it for us!\n";
  603     return 0;
  604   }
  605 
  606   # write the tex file
  607   local *TEX;
  608   open TEX, ">", $texFile or warn "Failed to create $texFile: $!";
  609   print TEX <<'EOF';
  610 % BEGIN HEADER
  611 \batchmode
  612 \documentclass[12pt]{article}
  613 \usepackage{amsmath,amsfonts,amssymb}
  614 \def\gt{>}
  615 \def\lt{<}
  616 \usepackage[active,textmath,displaymath]{preview}
  617 \begin{document}
  618 % END HEADER
  619 EOF
  620   print TEX "\\( \\displaystyle{$tex} \\)\n";
  621   print TEX <<'EOF';
  622 % BEGIN FOOTER
  623 \end{document}
  624 % END FOOTER
  625 EOF
  626   close TEX;
  627 
  628   # call latex
  629   system "cd $wd && $latex $texFile > /dev/null"
  630     and warn "Failed to call $latex with $texFile: $!";
  631 
  632   unless (-e $dviFile) {
  633     warn "Failed to generate DVI file $dviFile";
  634     return 0;
  635   }
  636 
  637   if ($dvipngBroken) {
  638     # change the name of the DVI file to get around dvipng's
  639     # crackheadedness. This is no longer needed with the newest
  640     # version of dvipng (10 something)
  641     system "/bin/mv", $dviFile, $dviFile2;
  642   }
  643 
  644   # call dvipng -- using warn instead of die passes some extra information
  645   # back to the user the complete warning is still printed in the apache
  646   # error log and a simple message (math2img failed) is returned to the
  647   # webpage.
  648   my $cmdout;
  649   $cmdout = system "cd $wd && $dvipng $dviCall > /dev/null"
  650     and warn "Failed to call$dvipng with $dviCall: $! with signal $cmdout";
  651 
  652   unless (-e $pngFile) {
  653     warn "Failed to create PNG file $pngFile";
  654     return 0;
  655   }
  656 
  657   $cmdout = system "/bin/mv", $pngFile, $targetPath and warn "Failed to mv: /bin/mv  $pngFile $targetPath $!. Call returned $cmdout. \n";
  658 }
  659 
  660 
  661 # ----- ----- ----- -----
  662 
  663 =head2  alias
  664 
  665   alias(pathToFile);
  666     returns A string describing the URL which links to GIF or html file
  667             (in HTML and Latex2HTML modes).
  668             or a path to the appropriate eps version of a GIF file
  669              (TeX Mode)
  670 
  671 
  672 
  673 C<alias> allows you to refer to auxiliary files which are in a directory along with
  674 the problem definition.  In addition alias creates an eps copy of GIF files when
  675 downloading hard copy (TeX mode).
  676 
  677 As a rule auxiliary files that are used by
  678 a number of problems in a course should be placed in C<html/gif> or C<html>
  679 or in a subdirectory of the C<html> directory,
  680 while auxiliary files which are used in only one problem should be placed in
  681 the same directory as the problem in order to make the problem more portable.
  682 
  683 
  684 
  685 =over 4
  686 
  687 =item  Files in the html subdirectory
  688 
  689 B<When not in TeX mode:>
  690 
  691 If the file lies under the C<html> subdirectory, then the approriate URL for the file is created.
  692 Since the C<html> subdirectory is already accessible to the webserver no other changes need to be made.
  693 The file path for this type of file should be the complete file path. The path should
  694 start with the prefix defined in $Global:htmlDirectory.
  695 
  696 B<When in TeX mode:>
  697 
  698 
  699 GIF files will be translated into an eps file (using system dependent code)
  700 and placed in the directory C<tmp/eps>.  The full path to this file is returned
  701 for use by TeX in producing the hard copy. (This should work even in a chrooted
  702 environment.) in producing the hard copy.   (This should work even in a chrooted
  703 environment.)
  704 
  705 The conversion is done by a system dependent script
  706 called C<gif2eps> which should be in the scripts directory
  707 
  708 The URL's for the other files are produced as in non-tex mode
  709 but will of course not be active.
  710 
  711 =item  Files in the tmp subdirectory
  712 
  713 B<When not in TeX mode:>
  714 
  715 If the file lies under the C<tmp> subdirectory, then the approriate URL for the file is created.
  716 Since the C<tmp> subdirectory is already accessible to the webserver no other changes need to be made.
  717 The file path for this type of file should be the complete file path. The path should
  718 start with the prefix defined in $Global:tempDirectory.
  719 
  720 B<When in TeX mode:>
  721 
  722 
  723 GIF files will be translated into an eps file (using system dependent code)
  724 and placed in the directory C<tmp/eps>.  The full path to this file is returned
  725 for use by TeX in producing the hard copy.  (This should work even in a chrooted
  726 environment.)
  727 
  728 The conversion is done by a system dependent script
  729 called C<gif2eps> which should be in the scripts directory
  730 
  731 The URL's for the other files are produced as in non-tex mode
  732 but will of course not be active.
  733 
  734 =item Files in the course template subdirectory:
  735 
  736 B<When not in TeX mode:>
  737 
  738 If the file lies under the course templates subdirectory,
  739 it is assumed to lie in subdirectory rooted in the directory
  740 containing the problem template file.
  741 An alias is created under the C<html/tmp/gif> or
  742 C<html/tmp/html> directory and linked to the original file.
  743 The file path for this type of file is a relative
  744 path rooted at the directory containing the problem template file.
  745 
  746 B<When in TeX mode:>
  747 
  748 GIF files will be translated into an eps file (using system dependent code)
  749 and placed in the directory C<html/tmp/eps>.  The full path to this file is returned
  750 for use by TeX in producing the hard copy.   (This should work even in a chrooted
  751 environment.)
  752 
  753 The conversion is done by a system dependent script
  754 called C<gif2eps> which should be in the scripts directory
  755 
  756 The URL's for the other files are produced as in non-tex mode
  757 but will of course not be active.
  758 
  759 =back
  760 
  761 =cut
  762 
  763 
  764 
  765 # Currently gif, html and types are supported.
  766 #
  767 # If the auxiliary file path has not extension then the extension .gif isassumed.
  768 #
  769 # If the auxiliary file path leads to a file in the ${Global::htmlDirectory}
  770 # no changes are made to the file path.
  771 #
  772 # If the auxiliary file path is not complete, than it is assumed that it refers
  773 # to a subdirectoy of the directory containing the problem..
  774 #
  775 # The output is either the correct URL for the file
  776 # or (in TeX mode) the complete path to the eps version of the file
  777 # and can be used as input into the image macro.
  778 #
  779 # surePathToTmpFile takes a path and outputs the complete path:
  780 # ${main::htmlDirectory}/tmp/path
  781 # It insures that all of the directories in the path have been created,
  782 # but does not create the
  783 # final file.
  784 
  785 # For postscript printing, alias generates an eps version of the gif image and places
  786 # it in the directory eps.  This slows down downloading postscript versions somewhat,
  787 # but not excessivevly.
  788 # Alias does not do any garbage collection, so files and alias may accumulate and
  789 # need to be removed manually or by a reaper daemon.
  790 
  791 
  792 # Global variables used:
  793 #  $main::fileName  # the full path to the current problem template file
  794 #  $main::htmlDirectory
  795 #  $main::htmlURL
  796 #  $main::tempDirectory
  797 #  $main::tempURL
  798 #  $main::studentLogin
  799 #  $main::psvnNumber
  800 #  $main::setNumber
  801 #  $main::probNum
  802 #  $main::displayMode
  803 
  804 # Global macros used
  805 # gif2eps   An external file called by system
  806 # surePathToTmpFile
  807 # convertPath
  808 # directoryFromPath
  809 
  810 
  811 # This subroutine  has commands which will not work on non-UNIX environments.
  812 # system("cat $gifSourceFile  | /usr/math/bin/giftopnm | /usr/math/bin/pnmdepth 1 | /usr/math/bin/pnmtops -noturn>$adr_output") &&
  813 
  814 
  815 # local constants $User, $psvn $setNumber $probNum $displayMode
  816 
  817 sub sourceAlias {
  818   my $path_to_file = shift;
  819   my $envir        =  PG_restricted_eval(q!\%main::envir!);
  820   my $user         = $envir->{inputs_ref}->{user};
  821   $user            = " " unless defined($user);
  822     my $out = 'source.pl?probSetKey='  . $envir->{psvn}.
  823           '&amp;probNum='          . $envir->{probNum} .
  824           '&amp;Mode='             . $envir->{displayMode} .
  825           '&amp;course='           . $envir->{courseName} .
  826           '&amp;user='             . $user .
  827         '&amp;displayPath='      . $path_to_file .
  828           '&amp;key='              . $envir->{sessionKey};
  829 
  830    $out;
  831 }
  832 
  833 
  834 sub alias {
  835   # input is a path to the original auxiliary file
  836   my $envir               = eval(q!\%main::envir!);  # get the current root environment
  837     my $fileName            = $envir->{fileName};
  838   my $htmlDirectory       = $envir->{htmlDirectory};
  839   my $htmlURL             = $envir->{htmlURL};
  840   my $tempDirectory       = $envir->{tempDirectory};
  841   my $tempURL             = $envir->{tempURL};
  842   my $studentLogin        = $envir->{studentLogin};
  843   my $psvnNumber          = $envir->{psvnNumber};
  844   my $setNumber           = $envir->{setNumber};
  845   my $probNum             = $envir->{probNum};
  846   my $displayMode         = $envir->{displayMode};
  847     my $externalGif2EpsPath = $envir->{externalGif2EpsPath};
  848     my $externalPng2EpsPath = $envir->{externalPng2EpsPath};
  849 
  850   my $aux_file_path = shift @_;
  851   warn "Empty string used as input into the function alias" unless $aux_file_path;
  852 
  853   # problem specific data
  854   warn "The path to the current problem file template is not defined."     unless $fileName;
  855   warn "The current studentLogin is not defined "                          unless $studentLogin;
  856   warn "The current problem set number is not defined"                     if $setNumber eq ""; # allow for sets equal to 0
  857   warn "The current problem number is not defined"                         if $probNum eq "";
  858   warn "The current problem set version number (psvn) is not defined"      unless defined($psvnNumber);
  859   warn "The displayMode is not defined"                                    unless $displayMode;
  860 
  861   # required macros
  862   warn "The macro &surePathToTmpFile can't be found" unless defined(&surePathToTmpFile);
  863   warn "The macro &convertPath can't be found" unless defined(&convertPath);
  864   warn "The macro &directoryFromPath can't be found" unless defined(&directoryFromPath);
  865   warn "The webwork server does not have permission to execute the gif2eps script at  ${externalGif2EpsPath}." unless ( -x "${externalGif2EpsPath}" );
  866   warn "The webwork server does not have permission to execute the png2eps script at ${externalPng2EpsPath}." unless ( -x "${externalPng2EpsPath}" );
  867 
  868   # required directory addresses (and URL address)
  869   warn "htmlDirectory is not defined in $htmlDirectory" unless $htmlDirectory;
  870   warn "htmlURL is not defined in \$htmlURL" unless $htmlURL;
  871   warn "tempURL is not defined in \$tempURL" unless $tempURL;
  872 
  873   # determine extension, if there is one
  874   # if extension exists, strip and use the value for $ext
  875   # files without extensions are considered to be picture files:
  876 
  877   my $ext;
  878   if ($aux_file_path =~ s/\.([^\.]*)$// ) {
  879     $ext = $1;
  880   } else {
  881     warn "This file name $aux_file_path did not have an extension.<BR> " .
  882          "Every file name used as an argument to alias must have an extension.<BR> " .
  883          "The permissable extensions are .gif, .png, and .html .<BR>";
  884     $ext  = "gif";
  885   }
  886 
  887   # $adr_output is a url in HTML and Latex2HTML modes
  888   # and a complete path in TEX mode.
  889   my $adr_output;
  890 
  891   # in order to facilitate maintenance of this macro the routines for handling
  892   # different file types are defined separately.  This involves some redundancy
  893   # in the code but it makes it easier to define special handling for a new file
  894   # type, (but harder to change the behavior for all of the file types at once
  895   # (sigh)  ).
  896 
  897 
  898   if ($ext eq 'html') {
  899     ################################################################################
  900     # .html FILES in HTML, HTML_tth, HTML_dpng, HTML_img, etc. and Latex2HTML mode
  901     ################################################################################
  902 
  903     # No changes are made for auxiliary files in the
  904     # ${Global::htmlDirectory} subtree.
  905     if ( $aux_file_path =~ m|^$tempDirectory| ) {
  906       $adr_output = $aux_file_path;
  907       $adr_output =~ s|$tempDirectory|$tempURL/|;
  908       $adr_output .= ".$ext";
  909     } elsif ($aux_file_path =~ m|^$htmlDirectory| ) {
  910       $adr_output = $aux_file_path;
  911       $adr_output =~ s|$htmlDirectory|$htmlURL|;
  912       $adr_output .= ".$ext";
  913     } else {
  914       # HTML files not in the htmlDirectory are assumed under live under the
  915       # templateDirectory in the same directory as the problem.
  916       # Create an alias file (link) in the directory html/tmp/html which
  917       # points to the original file and return the URL of this alias.
  918       # Create all of the subdirectories of html/tmp/html which are needed
  919       # using sure file to path.
  920 
  921       # $fileName is obtained from environment for PGeval
  922       # it gives the  full path to the current problem
  923       my $filePath = directoryFromPath($fileName);
  924       my $htmlFileSource = convertPath("$templateDirectory${filePath}$aux_file_path.html");
  925       my $link = "html/$studentLogin-$psvnNumber-set$setNumber-prob$probNum-$aux_file_path.$ext";
  926       my $linkPath = surePathToTmpFile($link);
  927       $adr_output = "${tempURL}$link";
  928       if (-e $htmlFileSource) {
  929         if (-e $linkPath) {
  930           unlink($linkPath) || warn "Unable to unlink alias file at |$linkPath|";
  931           # destroy the old link.
  932         }
  933         symlink( $htmlFileSource, $linkPath)
  934               || warn "The macro alias cannot create a link from |$linkPath|  to |$htmlFileSource| <BR>" ;
  935       } else {
  936         warn("The macro alias cannot find an HTML file at: |$htmlFileSource|");
  937       }
  938     }
  939   } elsif ($ext eq 'gif') {
  940     if ( $displayMode eq 'HTML' ||
  941          $displayMode eq 'HTML_tth'||
  942          $displayMode eq 'HTML_dpng'||
  943          $displayMode eq 'HTML_asciimath'||
  944          $displayMode eq 'HTML_jsMath'||
  945          $displayMode eq 'HTML_img'||
  946          $displayMode eq 'Latex2HTML')  {
  947       ################################################################################
  948       # .gif FILES in HTML, HTML_tth, HTML_dpng, HTML_img, and Latex2HTML modes
  949       ################################################################################
  950 
  951       #warn "tempDirectory is $tempDirectory";
  952       #warn "file Path for auxiliary file is $aux_file_path";
  953 
  954       # No changes are made for auxiliary files in the htmlDirectory or in the tempDirectory subtree.
  955       if ( $aux_file_path =~ m|^$tempDirectory| ) {
  956         $adr_output = $aux_file_path;
  957         $adr_output =~ s|$tempDirectory|$tempURL|;
  958         $adr_output .= ".$ext";
  959         #warn "adress out is $adr_output";
  960       } elsif ($aux_file_path =~ m|^$htmlDirectory| ) {
  961         $adr_output = $aux_file_path;
  962         $adr_output =~ s|$htmlDirectory|$htmlURL|;
  963         $adr_output .= ".$ext";
  964       } else {
  965         # files not in the htmlDirectory sub tree are assumed to live under the templateDirectory
  966         # subtree in the same directory as the problem.
  967 
  968         # For a gif file the alias macro creates an alias under the html/images directory
  969         # which points to the gif file in the problem directory.
  970         # All of the subdirectories of html/tmp/gif which are needed are also created.
  971         my $filePath = directoryFromPath($fileName);
  972 
  973         # $fileName is obtained from environment for PGeval
  974         # it gives the full path to the current problem
  975         my $gifSourceFile = convertPath("$templateDirectory${filePath}$aux_file_path.gif");
  976         #my $link = "gif/$studentLogin-$psvnNumber-set$setNumber-prob$probNum-$aux_file_path.$ext";
  977         my $link = "gif/$setNumber-prob$probNum-$aux_file_path.$ext";
  978 
  979         my $linkPath = surePathToTmpFile($link);
  980         $adr_output = "${tempURL}$link";
  981         #warn "linkPath is $linkPath";
  982         #warn "adr_output is $adr_output";
  983         if (-e $gifSourceFile) {
  984           if (-e $linkPath) {
  985             unlink($linkPath) || warn "Unable to unlink old alias file at $linkPath";
  986           }
  987           symlink($gifSourceFile, $linkPath)
  988             || warn "The macro alias cannot create a link from |$linkPath|  to |$gifSourceFile| <BR>" ;
  989         } else {
  990           warn("The macro alias cannot find a GIF file at: |$gifSourceFile|");
  991         }
  992       }
  993     } elsif ($displayMode eq 'TeX') {
  994       ################################################################################
  995       # .gif FILES in TeX mode
  996       ################################################################################
  997 
  998       if ($envir{texDisposition} eq "pdf") {
  999         # We're going to create PDF files with our TeX (using pdflatex), so we
 1000         # need images in PNG format.
 1001 
 1002         my $gifFilePath;
 1003 
 1004         if ($aux_file_path =~ m/^$htmlDirectory/ or $aux_file_path =~ m/^$tempDirectory/) {
 1005           # we've got a full pathname to a file
 1006           $gifFilePath = "$aux_file_path.gif";
 1007         } else {
 1008           # we assume the file is in the same directory as the problem source file
 1009           $gifFilePath = $templateDirectory . directoryFromPath($fileName) . "$aux_file_path.gif";
 1010         }
 1011 
 1012         my $gifFileName = fileFromPath($gifFilePath);
 1013 
 1014         $gifFileName =~ /^(.*)\.gif$/;
 1015         my $pngFilePath = surePathToTmpFile("${tempDirectory}png/$probNum-$1.png");
 1016         my $returnCode = system "$envir{externalGif2PngPath} $gifFilePath $pngFilePath";
 1017 
 1018         if ($returnCode or not -e $pngFilePath) {
 1019           die "failed to convert $gifFilePath to $pngFilePath using gif->png with $envir{externalGif2PngPath}: $!\n";
 1020         }
 1021 
 1022         $adr_output = $pngFilePath;
 1023       } else {
 1024         # Since we're not creating PDF files, we're probably just using a plain
 1025         # vanilla latex. Hence, we need EPS images.
 1026 
 1027         ################################################################################
 1028         # This is statement used below is system dependent.
 1029         # Notice that the range of colors is restricted when converting to postscript to keep the files small
 1030         # "cat $gifSourceFile  | /usr/math/bin/giftopnm | /usr/math/bin/pnmtops -noturn > $adr_output"
 1031         # "cat $gifSourceFile  | /usr/math/bin/giftopnm | /usr/math/bin/pnmdepth 1 | /usr/math/bin/pnmtops -noturn > $adr_output"
 1032         ################################################################################
 1033         if ($aux_file_path =~  m|^$htmlDirectory|  or $aux_file_path =~  m|^$tempDirectory|)  {
 1034           # To serve an eps file copy an eps version of the gif file to the subdirectory of eps/
 1035           my $linkPath = directoryFromPath($fileName);
 1036 
 1037           my $gifSourceFile = "$aux_file_path.gif";
 1038           my $gifFileName = fileFromPath($gifSourceFile);
 1039           $adr_output = surePathToTmpFile("$tempDirectory/eps/$studentLogin-$psvnNumber-$gifFileName.eps") ;
 1040 
 1041           if (-e $gifSourceFile) {
 1042             #system("cat $gifSourceFile  | /usr/math/bin/giftopnm | /usr/math/bin/pnmdepth 1 | /usr/math/bin/pnmtops -noturn>$adr_output")
 1043             system("${externalGif2EpsPath} $gifSourceFile $adr_output" )
 1044               && die "Unable to create eps file:\n |$adr_output| from file\n |$gifSourceFile|\n in problem $probNum " .
 1045                      "using the system dependent script\n |${externalGif2EpsPath}| \n";
 1046           } else {
 1047             die "|$gifSourceFile| cannot be found.  Problem number: |$probNum|";
 1048           }
 1049         } else {
 1050           # To serve an eps file copy an eps version of the gif file to  a subdirectory of eps/
 1051           my $filePath = directoryFromPath($fileName);
 1052           my $gifSourceFile = "${templateDirectory}${filePath}$aux_file_path.gif";
 1053           #print "content-type: text/plain \n\nfileName = $fileName and aux_file_path =$aux_file_path<BR>";
 1054           $adr_output = surePathToTmpFile("eps/$studentLogin-$psvnNumber-set$setNumber-prob$probNum-$aux_file_path.eps");
 1055 
 1056           if (-e $gifSourceFile) {
 1057             #system("cat $gifSourceFile  | /usr/math/bin/giftopnm | /usr/math/bin/pnmdepth 1 | /usr/math/bin/pnmtops -noturn>$adr_output") &&
 1058             #warn "Unable to create eps file: |$adr_output|\n from file\n |$gifSourceFile|\n in problem $probNum";
 1059             #warn "Help ${:externalGif2EpsPath}" unless -x "${main::externalGif2EpsPath}";
 1060             system("${externalGif2EpsPath} $gifSourceFile $adr_output" )
 1061               && die "Unable to create eps file:\n |$adr_output| from file\n |$gifSourceFile|\n in problem $probNum " .
 1062                      "using the system dependent script\n |${externalGif2EpsPath}| \n ";
 1063           }  else {
 1064             die "|$gifSourceFile| cannot be found.  Problem number: |$probNum|";
 1065           }
 1066         }
 1067       }
 1068     } else {
 1069       die "Error in alias: dangerousMacros.pl: unrecognizable displayMode = $displayMode";
 1070     }
 1071   } elsif ($ext eq 'png') {
 1072     if ( $displayMode eq 'HTML' ||
 1073          $displayMode eq 'HTML_tth'||
 1074          $displayMode eq 'HTML_dpng'||
 1075          $displayMode eq 'HTML_asciimath'||
 1076          $displayMode eq 'HTML_jsMath'||
 1077          $displayMode eq 'HTML_img'||
 1078          $displayMode eq 'Latex2HTML')  {
 1079       ################################################################################
 1080       # .png FILES in HTML, HTML_tth, HTML_dpng, HTML_img, etc. and Latex2HTML modes
 1081       ################################################################################
 1082 
 1083       #warn "tempDirectory is $tempDirectory";
 1084       #warn "file Path for auxiliary file is $aux_file_path";
 1085 
 1086       # No changes are made for auxiliary files in the htmlDirectory or in the tempDirectory subtree.
 1087       if ( $aux_file_path =~ m|^$tempDirectory| ) {
 1088       $adr_output = $aux_file_path;
 1089         $adr_output =~ s|$tempDirectory|$tempURL|;
 1090         $adr_output .= ".$ext";
 1091         #warn "adress out is $adr_output";
 1092       } elsif ($aux_file_path =~ m|^$htmlDirectory| ) {
 1093         $adr_output = $aux_file_path;
 1094         $adr_output =~ s|$htmlDirectory|$htmlURL|;
 1095         $adr_output .= ".$ext";
 1096       } else {
 1097         # files not in the htmlDirectory sub tree are assumed to live under the templateDirectory
 1098         # subtree in the same directory as the problem.
 1099 
 1100         # For a png file the alias macro creates an alias under the html/images directory
 1101         # which points to the png file in the problem directory.
 1102         # All of the subdirectories of html/tmp/gif which are needed are also created.
 1103         my $filePath = directoryFromPath($fileName);
 1104 
 1105         # $fileName is obtained from environment for PGeval
 1106         # it gives the full path to the current problem
 1107         my $pngSourceFile = convertPath("$templateDirectory${filePath}$aux_file_path.png");
 1108         my $link = "gif/$studentLogin-$psvnNumber-set$setNumber-prob$probNum-$aux_file_path.$ext";
 1109         my $linkPath = surePathToTmpFile($link);
 1110         $adr_output = "${tempURL}$link";
 1111         #warn "linkPath is $linkPath";
 1112         #warn "adr_output is $adr_output";
 1113         if (-e $pngSourceFile) {
 1114           if (-e $linkPath) {
 1115             unlink($linkPath) || warn "Unable to unlink old alias file at $linkPath";
 1116           }
 1117           symlink($pngSourceFile, $linkPath)
 1118           || warn "The macro alias cannot create a link from |$linkPath|  to |$pngSourceFile| <BR>" ;
 1119         } else {
 1120           warn("The macro alias cannot find a PNG file at: |$pngSourceFile|");
 1121         }
 1122       }
 1123     } elsif ($displayMode eq 'TeX') {
 1124       ################################################################################
 1125       # .png FILES in TeX mode
 1126       ################################################################################
 1127 
 1128       if ($envir{texDisposition} eq "pdf") {
 1129         # We're going to create PDF files with our TeX (using pdflatex), so we
 1130         # need images in PNG format. what luck! they're already in PDF format!
 1131 
 1132         my $pngFilePath;
 1133 
 1134         if ($aux_file_path =~ m/^$htmlDirectory/ or $aux_file_path =~ m/^$tempDirectory/) {
 1135           # we've got a full pathname to a file
 1136           $pngFilePath = "$aux_file_path.png";
 1137         } else {
 1138           # we assume the file is in the same directory as the problem source file
 1139           $pngFilePath = $templateDirectory . directoryFromPath($fileName) . "$aux_file_path.png";
 1140         }
 1141 
 1142         $adr_output = $pngFilePath;
 1143       } else {
 1144         # Since we're not creating PDF files, we're probably just using a plain
 1145         # vanilla latex. Hence, we need EPS images.
 1146 
 1147         ################################################################################
 1148         # This is statement used below is system dependent.
 1149         # Notice that the range of colors is restricted when converting to postscript to keep the files small
 1150         # "cat $pngSourceFile  | /usr/math/bin/pngtopnm | /usr/math/bin/pnmtops -noturn > $adr_output"
 1151         # "cat $pngSourceFile  | /usr/math/bin/pngtopnm | /usr/math/bin/pnmdepth 1 | /usr/math/bin/pnmtops -noturn > $adr_output"
 1152         ################################################################################
 1153 
 1154         if ($aux_file_path =~  m|^$htmlDirectory|  or $aux_file_path =~  m|^$tempDirectory|)  {
 1155           # To serve an eps file copy an eps version of the png file to the subdirectory of eps/
 1156           my $linkPath = directoryFromPath($fileName);
 1157 
 1158           my $pngSourceFile = "$aux_file_path.png";
 1159           my $pngFileName = fileFromPath($pngSourceFile);
 1160           $adr_output = surePathToTmpFile("$tempDirectory/eps/$studentLogin-$psvnNumber-$pngFileName.eps") ;
 1161 
 1162           if (-e $pngSourceFile) {
 1163             #system("cat $pngSourceFile  | /usr/math/bin/pngtopnm | /usr/math/bin/pnmdepth 1 | /usr/math/bin/pnmtops -noturn>$adr_output")
 1164             system("${externalPng2EpsPath} $pngSourceFile $adr_output" )
 1165               && die "Unable to create eps file:\n |$adr_output| from file\n |$pngSourceFile|\n in problem $probNum " .
 1166                      "using the system dependent script\n |${externalPng2EpsPath}| \n";
 1167           } else {
 1168             die "|$pngSourceFile| cannot be found.  Problem number: |$probNum|";
 1169           }
 1170         } else {
 1171           # To serve an eps file copy an eps version of the png file to  a subdirectory of eps/
 1172           my $filePath = directoryFromPath($fileName);
 1173           my $pngSourceFile = "${templateDirectory}${filePath}$aux_file_path.png";
 1174           #print "content-type: text/plain \n\nfileName = $fileName and aux_file_path =$aux_file_path<BR>";
 1175           $adr_output = surePathToTmpFile("eps/$studentLogin-$psvnNumber-set$setNumber-prob$probNum-$aux_file_path.eps") ;
 1176           if (-e $pngSourceFile) {
 1177             #system("cat $pngSourceFile  | /usr/math/bin/pngtopnm | /usr/math/bin/pnmdepth 1 | /usr/math/bin/pnmtops -noturn>$adr_output") &&
 1178             #warn "Unable to create eps file: |$adr_output|\n from file\n |$pngSourceFile|\n in problem $probNum";
 1179             #warn "Help ${externalPng2EpsPath}" unless -x "${externalPng2EpsPath}";
 1180             system("${externalPng2EpsPath} $pngSourceFile $adr_output" )
 1181               && die "Unable to create eps file:\n |$adr_output| from file\n |$pngSourceFile|\n in problem $probNum " .
 1182                      "using the system dependent script\n |${externalPng2EpsPath}| \n ";
 1183           } else {
 1184             die "|$pngSourceFile| cannot be found.  Problem number: |$probNum|";
 1185           }
 1186         }
 1187       }
 1188     } else {
 1189       warn  "Error in alias: dangerousMacros.pl","unrecognizable displayMode = $displayMode","";
 1190     }
 1191   } else { # $ext is not recognized
 1192     ################################################################################
 1193     # FILES  with unrecognized file extensions in any display modes
 1194     ################################################################################
 1195 
 1196     warn "Error in the macro alias. Alias does not understand how to process files with extension $ext.  (Path ot problem file is  $fileName) ";
 1197   }
 1198 
 1199   warn "The macro alias was unable to form a URL for some auxiliary file used in this problem." unless $adr_output;
 1200   return $adr_output;
 1201 }
 1202 
 1203 
 1204 
 1205 
 1206 
 1207 # Experiments
 1208 
 1209 # This allows the use of i for imaginary numbers
 1210 #  one can write  3+2*i  rather than  3+2*i()
 1211 #
 1212 
 1213 #sub i {
 1214 # Complex::i;
 1215 #}
 1216 
 1217 sub i () {
 1218   #  check if Parser.pl is loaded, otherwise use Complex package
 1219   if (eval(q!$main::_parser_loaded!)) {return Value::Formula->new('i')->eval}
 1220   Complex::i;
 1221 }
 1222 sub j () {
 1223   if (!eval(q!$main::_parser_loaded!)) {return 'j'}
 1224   Value::Formula->new('j')->eval
 1225 }
 1226 sub k () {
 1227   if (!eval(q!$main::_parser_loaded!)) {return 'k'}
 1228   Value::Formula->new('k')->eval;
 1229 }
 1230 
 1231 sub pi () {Value::Formula->new('pi')->eval}
 1232 sub Infinity () {Value::Infinity->new()}
 1233 
 1234 1;  # required to load properly

aubreyja at gmail dot com
ViewVC Help
Powered by ViewVC 1.0.9