﻿<?php

SDV($cc_cmd, "http://latex.codecogs.com/png.latex");
SDV($cc_arg, "?\bg_white&space;");
SDV($cache_dir, "pub/cache");
SDV($cache_url, $PubDirUrl."/cache");

Markup('{$', 'directives',
  '/\\{\\$(.*?)\\$\\}/e',
  "Keep(Codecogs(PSS('$1')))");

function Codecogs($tex) {
    global $cc_cmd;
    global $cc_arg;
    global $cache_dir;
    global $cache_url;

    $tex = trim($tex);
    $tex = str_replace(" ", "&space;", $tex);
    $img_name = md5($tex).".png";
    $img_path_l = $cache_dir."/".$img_name;
    $img_path_p = $cache_url."/".$img_name;

    $tex_alt = str_replace("'", "&#039;", $tex);
    $tex_alt = str_replace("\"", "&#034;", $tex);
    $tex_alt = str_replace("&space;", " ", $tex);

    $content = file_get_contents($cc_cmd.$cc_arg.$tex);
    $str = "<img align='absmiddle' class='mimetex' src='".$img_path_p."' alt='".$tex_alt."'>";

    if($content == false) {
        return("fault: unable to get image: $tex");
    }
    else {
        if(file_exists($img_path_l)) {
            return($str);
        }
        else {
            $f = fopen($img_path_l, "w");

            if($f == FALSE) {
                return("fault: unable to open image: $tex");
            }

            fwrite($f, $content);
            fclose($f);

            return($str);
        }
    }
}

?>
