<?php

class myToolkit
{
  private static function geshiCall($matches, $default = '')
  {
    require_once('geshi.php');

    if (preg_match('/^\[(.+?)\]\s*(.+)$/s', $matches[1], $match))
    {
      $geshi = new GeSHi(html_entity_decode($match[2]), $match[1]);
      $geshi->enable_classes();
      return @$geshi->parse_code();
    }
    else
    {
      if ($default)
      {
        $geshi = new GeSHi(html_entity_decode($matches[1]), $default);
        $geshi->enable_classes();

        return @$geshi->parse_code();
      }
      else
      {
        return "<pre><code>".$matches[1].'</pre></code>';
      }
    }
  }

  private static function geshiCallWithPHPAsDefault($matches)
  {
    return self::geshiCall($matches, 'php');
  }

  public static function transformToHtml($string)
  {
    $string = htmlentities($string, ENT_QUOTES, 'UTF-8');
    // transform [code] blocks to Markdown code blocks
    $lines  = explode("\n", $string);
    $incode = false;
    $string = '';
    foreach ($lines as $line)
    {
      if ($incode)
      {
        $line = '    '.html_entity_decode($line, ENT_QUOTES, 'UTF-8');
      }
      if (preg_match('/^\s*\[code\s*([^\]]*?)\]/', $line, $match))
      {
        $incode = true;
        $line   = $match[1] ? "\n\n    [".$match[1]."]" : "\n\n";
      }
      if (strpos($line, '[/code]') !== false)
      {
        $incode = false;
        $line   = ' ';
      }

      $string .= $line."\n";
    }

    // Markdown formatting
    require_once('markdown.php');
    $html = markdown($string);

    // change class for command line stuff
    $html = preg_replace('/<pre><code>\$ /s', '<pre class="command-line"><code>$ ', $html);

    // change class for http:// link
    $html = preg_replace('#<pre><code>http\://#s', '<pre class="url"><code>http://', $html);

    // syntax highlighting
    $html = preg_replace_callback('#<pre><code>(.+?)</code></pre>#s', array('myToolkit', 'geshiCallWithPHPAsDefault'), $html);

    return $html;
  }
}

?>
