NagVis with MK Livestats compatible json_decode()

3
Feb/10
2

When installing the latest version of Nagvis (1.4.5) on my a RHEL 5.4 Apache instance (PHP 5.1) I really wanted it to connect to the new and cool MK Livestats backend for Nagios. Too bad the apparently recently added json_decode() function wasn’t tested for compatibility and it breaks Nagvis. Luckily the round-about-fix isn’t that complicated and just fits in the current design of Nagvis.

To bugfix please edit your “nagvis/includes/functions/oldPhpVersionFixes.php” file and add (or replace if already present) the code below.

/**
 * JSON Decode to PHP
 * (Needed for PHP < 5.2.0)
 *
 * Function cannot compete with commented JSON inputs, please remove all
 * comments prior to input. Not tested with any other software other then
 * NagVis requirements.
 *
 * @param   String      JSON formatted code
 * @author  Emil Wayers
 * @version 1.0
 */
if(!function_exists('json_decode')){

  function json_decode($json) {

    $json = str_replace(array("\n","\r"), "", $json);
    $json = preg_replace('/([{,])(s*)([^"]+?)s*:/' , '$1"$3":', $json);

    $out = '$x=';

    $inside_value=false;

    for ($i=0; $i<strlen($json); $i++) {
      if($json[$i] == '"') {
        $inside_value = !$inside_value;
      }

      if($inside_value) {
        $out .= $json[$i];

      } else {
        switch($json[$i]) {
          case "{": $out .= " array("; break;
          case "}": $out .= ")";       break;
          case "[": $out .= " array("; break;
          case "]": $out .= ")";       break;
          case ":": $out .= "=>";      break;
          default:
            $out .= $json[$i];
        }
      }
    }

    eval($out . ';');
    return $x;
  }
}

I also found a very good hint that this issue will be resolved within the next release…

Update: You can always, pear install pecl/json