<?php
/*  Copyright 2004 Patrick R. Michaud (pmichaud@pobox.com), based on
    code and suggestions by Christian Ridderström.

    To use this module, you need to do the following steps:
    1.  Download and build the mimeTeX package from 
        http://www.forkosh.dreamhost.com/mimetexmanual.html .
        You can install it anywhere you like.
    2.  If you want PmWiki to just create references to mimetex.cgi as
        a cgi-bin script, set $MimetexUrl to the url location of
        mimetex.cgi as built in step 1.
    3.  If you want PmWiki to call mimetex.cgi directly and cache the
        images, set $MimetexCmd to be the filesystem path of the
        mimetex.cgi program, create the directory pub/cache/, and
        give the pub/cache/ directory 777 permissions.
    4.  Include this script in your config.php file.

    For more information, see http://www.pmichaud.com/wiki/Cookbook/MimeTeX,
    or ask the pmwiki-users mailing list.

    Copyright 2023 V.Krishn (vkrishn@insteps.net)
    1.  Update to work with PHP-5.5x
    2.  Add $MimetexImgHash option
*/

SDV($MimetexUrl,"/cgi-bin/mimetex.cgi");
SDV($ImgCacheDir,"pub/cache");
SDV($ImgCacheUrl,"$PubDirUrl/cache");
SDV($MimetexImgHash,"md5");

if(function_exists('Markup_e')) {
  # new format, no /e , IMPORTANT: pmwiki-2.2.58+ and php 5.5x
  Markup('{$', 'directives', '/\\{\\$(.*?)\\$\\}/', 'CallbackMimetex');
} else {
  /* old format, for pmwiki < 2.2.58
     if using php 5.5x see pmwiki documentation as how to suppress
       deprecated preg_replace errors. */
  Markup('{$', 'directives', '/\\{\\$(.*?)\\$\\}/e', "Keep(Mimetex(PSS('$1')))");
}

function CallbackMimetex($m) {
  return Keep(Mimetex(PSS($m[0])));
}

SDV($GUIButtons['math'],array(1000, '{$ ', ' $}', '\\\\sqrt{n}', 
  '$GUIButtonDirUrlFmt/math.gif"$[Math formula (LaTeX/MimeTeX)]"'));

function Mimetex($tex) {
  global $MimetexCmd, $MimetexUrl, $ImgCacheDir, $ImgCacheUrl, $MimetexImgHash;
  $tex = trim("$tex");
  if (!@$MimetexCmd) {
    return "<img class='mimetex' src='$MimetexUrl?".rawurlencode($tex)."' 
      alt='".str_replace("'","&#039;",$tex)."' />";
  }
  $imgname = $MimetexImgHash($tex).".gif";
  mkdirp($ImgCacheDir); fixperms($ImgCacheDir);
  if (!file_exists("$ImgCacheDir/$imgname") &&  
      system("$MimetexCmd -d ".escapeshellarg($tex)." >$ImgCacheDir/$imgname")
        === false)
    return "mimetex-failed: $tex";
  return "<img ALIGN='absMIDDLE' class='mimetex' src='$ImgCacheUrl/$imgname' alt='".
    str_replace("'","&#039;",$tex)."' />";
}