<?php
session_start();
require_once 'db.php';
include_once "ewcfg12.php";
include_once "phpfn12.php";
include_once "class.user.php";

function gmp_rand($min, $max) {
    $max -= $min;
    $bit_length = strlen(gmp_strval($max, 2));

    do {
        $rand = gmp_init(0);
        for ($i = $bit_length - 1; $i >= 0; $i--) {
            gmp_setbit($rand, $i, rand(0, 1));
            if ($rand > $max) break;
        }
    } while ($rand > $max);

    return $rand + $min;
}

function array_weighted_rand ($list) {
    $total_weight = gmp_init(0);
    foreach ($list as $weight) {
        $total_weight += $weight;
    }

    $rand = gmp_rand(1, $total_weight);
    foreach ($list as $key => $weight) {
        $rand -= $weight;
        if ($rand <= 0) return $key;
    }
}

function fill_word ($word, $length, $trigrams) {
    while (strlen($word) < $length) {
        $word .= array_weighted_rand($trigrams[substr($word, -2)]);
    }
    return $word;
}

// Create an HTML Img Tag with Base64 Image Data
function gdImgToHTML( $gdImg, $format='jpg' ) {
    // Validate Format
    if( in_array( $format, array( 'jpg', 'jpeg', 'png', 'gif' ) ) ) {
        ob_start();

        if( $format == 'jpg' || $format == 'jpeg' ) {
            imagejpeg( $gdImg );
        } elseif( $format == 'png' ) {
            imagepng( $gdImg );
        } elseif( $format == 'gif' ) {
            imagegif( $gdImg );
        }

        $data = ob_get_contents();
        ob_end_clean();

        // Check for gd errors / buffer errors
        if( !empty( $data ) ) {
            $data = base64_encode( $data );

            // Check for base64 errors
            if ( $data !== false ) {
                // Success
                return "<img src='data:image/$format;base64,$data'>";
            }
        }
    }

    // Failure
    return '<img>';
}

$user     = new USER($DB_con);

// storing  request (ie, get/post) global array to a variable
$req   = $_REQUEST;
$uname = $req['loginID'];

if($user->checkLoginID($uname)) {
  // to get rowCount to work, need to add the array parameter for the prepare function
  $stmt = $DB_con->prepare("SELECT USERSECUREWORD FROM WEBUSER WHERE USERID=:uname", array(PDO::ATTR_CURSOR => PDO::CURSOR_SCROLL));
  $stmt->execute(array(':uname'=>$uname));
  $row=$stmt->fetch(PDO::FETCH_ASSOC);

  // Create the image
  $im = imagecreatetruecolor(296, 30);

  // Create some colors
  $white = imagecolorallocate($im, 255, 255, 255);
  $grey  = imagecolorallocate($im, 128, 128, 128);
  $black = imagecolorallocate($im, 0, 0, 0);
  imagefilledrectangle($im, 0, 0, 296, 29, $white);

  // The text to draw
  $text = $row['USERSECUREWORD'];
  // Replace path by your own font path
  $font = 'phpfont/arial.ttf';

  // Add some shadow to the text
  imagettftext($im, 20, 0, 11, 26, $grey, $font, $text);

  // Add the text
  imagettftext($im, 20, 0, 10, 25, $black, $font, $text);

  // Using imagepng() results in clearer text compared with imagejpeg()
  //imagepng($im);  
  
  echo gdImgToHTML( $im, "png" );
  imagedestroy($im);  
  
  //echo "success";
} else {
  // not a valid user, randomly generate a SecureWord
  $lengths  = json_decode(file_get_contents('phpdict/distinct_word_lengths.json'), true);
  $bigrams  = json_decode(file_get_contents('phpdict/word_start_bigrams.json'), true);
  $trigrams = json_decode(file_get_contents('phpdict/trigrams.json'), true);


  $length = array_weighted_rand($lengths);
  $start  = array_weighted_rand($bigrams);
  $word   = fill_word($start, $length, $trigrams);

  $word = strtolower($word); 

  // Create the image
  $im = imagecreatetruecolor(296, 30);

  // Create some colors
  $white = imagecolorallocate($im, 255, 255, 255);
  $grey  = imagecolorallocate($im, 128, 128, 128);
  $black = imagecolorallocate($im, 0, 0, 0);
  imagefilledrectangle($im, 0, 0, 296, 29, $white);

  // The text to draw
  $text = $word;
  // Replace path by your own font path
  $font = 'phpfont/arial.ttf';

  // Add some shadow to the text
  imagettftext($im, 20, 0, 11, 26, $grey, $font, $text);

  // Add the text
  imagettftext($im, 20, 0, 10, 25, $black, $font, $text);

  // Using imagepng() results in clearer text compared with imagejpeg()
  //imagepng($im);  
  
  echo gdImgToHTML( $im, "png" );
  imagedestroy($im);  
  //echo "fail";
}

?>
