<?php /*

 Composr
 Copyright (c) ocProducts, 2004-2016

 See text/EN/licence.txt for full licencing information.


 NOTE TO PROGRAMMERS:
   Do not edit this file. If you need to make changes, save your changed file to the appropriate *_custom folder
   **** If you ignore this advice, then your website upgrades (e.g. for bug fixes) will likely kill your changes ****

*/

/**
 * @license    http://opensource.org/licenses/cpal_1.0 Common Public Attribution License
 * @copyright  ocProducts Ltd
 * @package    core
 */

/*
Examples...

'hello' --> 1
't2D' --> 2
't2D$' --> 3
't2D$f3t4t412%$' --> 9
*/

/**
 * Test password strength.
 *
 * @param  string $password The password to check
 * @param  string $username The username that will go with the password
 * @return integer Password strength (1-10)
 */
function test_password($password, $username = '')
{
    $strength = 1;

    if (strlen($password) == 0) {
        return $strength;
    }

    if (($username != '') && ($username == $password)) {
        return $strength;
    }

    // Check if password is not all lower case
    if (strtolower($password) != $password) {
        $strength += 5;
    }

    // Check if password is not all upper case
    if (strtoupper($password) != $password) {
        $strength += 5;
    }

    // Check string length
    $length = strlen($password);
    if ($length >= 8 && $length <= 15) {
        $strength += 16;
    } elseif ($length >= 16 && $length <= 35) {
        $strength += 32; // Check if length greater than 35 chars
    } elseif ($length > 35) {
        $strength += 48;
    }

    $matches = array();

    // Get the numbers in the password
    $strength += preg_match_all('#[0-9]#', $password, $matches) * 3;

    // Check for special chars
    $strength += preg_match_all('#[^a-zA-Z0-9]#', $password, $matches) * 8;

    // Get the number of unique chars
    $chars = preg_split('#(.)#', $password, -1, PREG_SPLIT_DELIM_CAPTURE);
    $num_unique_chars = count(array_unique($chars)) - 1;
    $strength += ($num_unique_chars - 1) * 2;

    // Strength must be a number 1-10
    return min(10, intval(round(floatval($strength) / 10.0)));
}
