<?php

class  CMsg
{
    var $success;
    var $status;
    var $message;
    var $fields;
    var $data;

    function __construct($success,$status = null,$message = null,$fields = null,$data = null)
    {
        $this->success = $success;
        $this->status = $status;
        $this->message = $message;
        $this->fields = $fields;
        $this->data = $data;
    }

    function jsonclass()
    {
        return json_encode($this);
    }

    function jsonarray()
    {
        return json_encode([
            'success' => $this->success,
            'status' => $this->status,
            'message' => $this->message,
            'fields' => $this->message,
            'data' => $this->data
        ]);
    }
}

class CUser
{
    var $id;
    var $qr_id;
    var $email;

    function __construct($id,$qr_id,$email)
    {
        $this->id = $id;
        $this->qr_id = $qr_id;
        $this->email = $email;
    }
    function jsonarray()
    {
        return json_encode([
            'id' => $this->id,
            'qr_id' => $this->qr_id,
            'email' => $this->email
        ]);
    }
    function phparray()
    {
        return ([
            'id' => $this->id,
            'qr_id' => $this->qr_id,
            'email' => $this->email
        ]);
    }

}

/**
 * Generate a random string, using a cryptographically secure 
 * pseudorandom number generator (random_int)
 * 
 * For PHP 7, random_int is a PHP core function
 * For PHP 5.x, depends on https://github.com/paragonie/random_compat
 * 
 * @param int $length      How many characters do we want?
 * @param string $keyspace A string of all possible characters
 *                         to select from
 * @return string
 */
function random_str(
    $length,
    $keyspace = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
) 
{
    $str = '';
    $max = mb_strlen($keyspace, '8bit') - 1;
    if ($max < 1) 
    {
        throw new Exception('$keyspace must be at least two characters long');
    }
    for ($i = 0; $i < $length; ++$i) 
    {
        $str .= $keyspace[random_int(0, $max)];
    }
    return $str;
}

function getNewFilename($targetDir, $fileExt, $length)
{
    $newFname = random_str($length);

//    echo "newFname   " . $newFname . "\n";

    $maxtries = 100000; // prevent endless loop, most unlikely 
    $tries = 0;
    // echo "file_exists   " . $targetDir . '/' . $newFname . '.' . $fileExt . "\n";
    // echo "file_exists   " . file_exists($targetDir . '/' . $newFname . '.' . $fileExt) . "\n";
    while(file_exists($targetDir . '/' . $newFname . '.' . $fileExt) && $tries < $maxtries)
    {
//        echo "file_exists   " . $targetDir . '/' . $newFname . '.' . $fileExt . "\n";
        ++$tries;
        $newFname = random_str($length);
        // echo "tries   " . $tries . "\n";
        // echo "newFname   " . $newFname . "\n";
    }
    if($tries >= $maxtries)
    {
        $newFname = "";
    }
    return $newFname .".".$fileExt;
}

?>
