<?php
class PasswordGenerator
{
	public static function generateSipPassword() {
		return PasswordGenerator::generatePassword(15, "_12346789bcdfghjkmnpqrtvwxyzBCDFGHJKLMNPQRTVWXYZ");
	}

	public static function generateUserPassword() {
        Yii::import('ext.PhonalisaValidators.passwordStrength');
        $passwordStrengthValidator = new passwordStrength();
        $password = "";

        for ($i = 0; $i<100; $i++) { // 100 tries to generate a valid paranoid password
            $password = PasswordGenerator::generatePassword(12);
            if ($passwordStrengthValidator->checkPasswordParanoid($password, "") == "") {
                break;
            }
        }

		return $password;
	}
	
	public static function generateUserPIN() {
		return PasswordGenerator::generatePassword(6, "0123456789");
	}
        
        public static function generateToken() {
            return PasswordGenerator::generatePassword(20, "12346789bcdfghjkmnpqrtvwxyzBCDFGHJKLMNPQRTVWXYZ");
        }

        public static function generatePassword($length, $possible= "_*#&/-!$\\()[]{}\\12346789bcdfghjkmnpqrtvwxyzBCDFGHJKLMNPQRTVWXYZ")  {

		$secret = NULL;
		$maxlength = strlen($possible);

		// check for length overflow and truncate if necessary
		if ($length > $maxlength) {
			$length = $maxlength;
		}

		$i = 0;
		// add random characters to $password until $length is reached
		while ($i < $length) {
			// pick a random character from the possible ones
			$char = substr($possible, mt_rand(0, $maxlength-1), 1);
			// have we already used this character in $password?
			if (!strstr($secret, $char)) {
				$secret .= $char;
				$i++;
			}

		}
		return $secret;
	}
	
	public static function cryptUserPassword($user, $pass) {
    	
    	if ($user == NULL) {
        	return NULL;
    	}
    	
    	if ($pass == "") {
        	return NULL;
    	}
    	
    	return md5($pass.$user->id);
    	
	}
}
